In the previous exercise checkpoint, you may have noticed that when we attempted to add DEBUG
messages to our calculator application, they didn’t appear in the console. What’s going on here?
Well, each logger object has a default set of log levels that will output unless a different log level is explicitly set. When we set a log level for a logger, any log message that has this log level and higher will output. The default log level is WARNING
in Python’s logging
module.
We used the default WARNING
level in the previous exercise, so only log messages with WARNING
level or higher were processed and logged to the console.
To change the default log level for a logger, we can use a method called setLevel(level)
. The level
parameter represents the numeric value of the log level to use. If we want the DEBUG
message to show from our previous exercise checkpoint, we can use the setLevel(level)
method like below:
logger.setLevel(logging.DEBUG)
This will set our log level to DEBUG
and allow all log messages with a severity of DEBUG
or higher to log to the console.
There are several cases where setting the log level can be helpful. If we are trying to troubleshoot a problem within our application that is causing it to crash, it would be optimal to see only the CRITICAL
level log messages and filter out all other messages.
If we are still in a development phase of our application and have to debug often, setting the log level to DEBUG
is useful for obtaining helpful debugging log messages. Once our application is ready for deployment, we can easily set the log level to WARNING
to filter out developer-friendly information like DEBUG
and INFO
messages.
Instructions
In our calculator application, after the logger object and handlers, set the log level for logger
to DEBUG
. Make sure to leave the last three lines of your program commented out for now.
Run the program by typing python3 script.py
in the terminal and clicking Enter. Click Check Work once the program is complete.
Uncomment the last three lines in the program. Inside the terminal output, execute python3 script.py
with the following inputs:
- Dividend = 6
- Divisor = 3
View the log statements that show in the terminal output. All log messages, including DEBUG
and INFO
messages, now show.