Log
Log messages can indicate an event has executed. You can use logging for these purposes:
- debugging
- informational messages
- show warnings
- show errors
- show critical messages
Overview:
To use start logging, load the logging module with "import logging".
import logging
logging.warning('File could not be opened')
We can use all the types of logging:
import logging
logging.debug('Debug message')
logging.info('Informational message')
logging.warning('Warning message')
logging.error('Error mesage')
logging.critical('Critical message')
Logging levels
You can add debug messages to your program, and on release change the logging level to information to hide them. It's also recommended to save logging messages to a file:
logging.basicConfig(filename='program.log',level=logging.INFO)
To return to debugging mode, change to:
logging.basicConfig(filename='program.log',level=logging.DEBUG)
The standard level is warning.
Practical example
An example of using the log module below:
import logging
x = int(raw_input("Enter a number: "))
if x < 0:
logging.error('Error: x must be positive.')
exit(0)
else:
print("Starting calculation")
logging.info("Calculation started.")
Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises