Part 1: Add logging to logging_demo
These exercises use the logging_demo.py
file.
- Complete the code for function
log_demo(logger)
.- Log one message using each of the 5 standard logging functions (debug, warning, info, error, critical or fatal).
- For each log level, write a message that is a good example of what you would log at that level.
- Write your own message, not something from the class presentation.
- Run the code (without any configuration of loggers).
- which log messages are printed?
- which log messages are not printed?
- In
__main__
, invokebasicConfig()
to initialize the logging facility, then calllog_demo
.- This causes
basicConfig
to use default values for all settings. - You must call this before any other logging calls, or it has no effect.
if __name__ == `__main__`: # basic config with default settings logging.basicConfig() logger = logging.getLogger() log_demo(logger)
Run the code.
- what changed?
- what do the fields in the output messages mean?
- This causes
- Create a named logger instead the default (root) logger. In
__main__
:logger = logging.getLogger("demo")
Run the code.
- how does the output change?
- In
__main__
add alevel=...
parameter to the call tobasicConfig
to set the threshold log level tologging.DEBUG
.logging.basicConfig(level=...)
Run the code again.
- what does
level=n
do? - what is the datatype of the level value? (int, str, something else?)
- Can you use
level=15
?level="DEBUG"
?
- what does
- Complete the
console_config
function. The function should set:- log threshold is WARNING
- log format is “{datetime} {loglevelname}: {message}”
- log output goes to the console (the default)
Modify main again:
- Remove call to
basicConfig
. - Invoke
console_config
instead.
Run it.
- How did the output change from previous case?
- Complete the
file_config
function. The function should use basicConfig to:- set log threshold is DEBUG
- log format is “{datetime} {logger_name} {loglevelname} {functionName}: {message}”
- functionName = name of function that logged the message
- send log messages to a file named
demo.log
- modify
__main__
to invokefile_config
instead ofconsole_config
.
Run the program.
- Did it print any messages on the console? (should not)
- Are messages logged to the file?
- If you run the code several times, what happens to the file
demo.log
? Does each run append messages to the file or overrite the old contents?- Does this make sense?
Push your final code to Github Classroom.
Logging and Log Formats
-
Python Logging complete documentation for logging, with links to tutorials & cookbook. Easy to understand after you read the Logging Howto.
-
Logging Formats section lists all the things you can include in the log message format.