Logging
Python hosting: PythonAnywhere — host, run and code Python in the cloud. Free tier available.
Python logging
We can track events in a software application, this is known as logging. Let's start with a simple example, we will log a warning message.As opposed to just printing the errors, logging can be configured to disable output or save to a file. This is a big advantage to simple printing the errors.
Related course
Practice Python with interactive exercises
Logging example
import logging
# print a log message to the console.
logging.warning('This is a warning!')
This will output:
WARNING:root:This is a warning!
We can easily output to a file:
import logging
logging.basicConfig(filename='program.log',level=logging.DEBUG)
logging.warning('An example message.')
logging.warning('Another message')
The importance of a log message depends on the severity.
Level of severity
The logger module has several levels of severity. We set the level of severity using this line of code:logging.basicConfig(level=logging.DEBUG)
These are the levels of severity:
| Type | Description |
|---|---|
| DEBUG | Information only for problem diagnostics |
| INFO | The program is running as expected |
| WARNING | Indicate something went wrong |
| ERROR | The software will no longer be able to function |
| CRITICAL | Very serious error |