setup
- import the logging module
- call
.basicConfig()
- setup autoreload to help reloading .py files from disk
### useful: please run this
import logging
logging.basicConfig()
%load_ext autoreload
%autoreload 2
Basic
- import
- Create a new python file named
ex1.py
which should:- Import the logging module
- create a logger instance named
__name__
- Create a function called
say_something()
that logs a ‘warning’ message with the text:"This a warning message!"
.
- use the file
import ex1
- call
ex1.say_something()
### useful: run your ex1.py
import ex1
ex1.say_something()
Log level
- Create a new python file named ‘ex2.py‘ which should:
- Import the logging module
- create a logger instance named
__name__
- set the logger’s level to
logging.DEBUG
- create a function called
say_something()
which logs an ‘info’ message with the text: “This an informative message!”.
- use this file
- import ex2
- call
ex2.say_something()
### useful: run your ex2.py
import ex2
ex2.say_something()
Configuration
- setup
- change the level of ex2’s logger to DEBUG
- call
ex2.say_something()
- this should write the usual output
- Review this basic YAML configuration, and see that you understand how it will:
- set a simple format that is the same as the default format
- set a handler that logs to console
- connect the root logger to the console handler, with level WARNING
- modify the level for the ex2 logger to ERROR
version: 1 disable_existing_loggers: False formatters: simple: format: '%(levelname)s:%(name)s:%(message)s' handlers: console: class: logging.StreamHandler formatter: simple stream: ext://sys.stderr loggers: ex2: level: ERROR root: level: WARNING handlers: [console]
- load this configuration
- import the
yaml
module - use
yaml.load()
to read this configuration into adict
object - import logging.config module
- use
logging.config.dictConfig()
function to load the configuration from your dict
- import the
- execute
ex2.say_something()
again. this time there should not be any output. why?
Format #1
Copy the YAML configuration from the previous question, and change the formatter so that output from calling ex1.say_something()
will look like this
2019-12-26 03:07:04,560 | WARNING | ex1 | this is a warning message
hints:
- Read the LogRecord documentaion, which shows the attributes available for formatting
Format #2
Copy the YAML configuration from the previous question, and change the formatter so that output from calling ex1.say_something()
will look like this:
2019-12-26 03:10:19,852 :: WARNING :: Module ex1 :: Line No 6 :: this is a warning message
file handler
- Use YAML configuration to
- set the levels of both
ex1
andex2
loggers to DEBUG - setup file logging for
ex2
logger so that it writes toex2.log
- set the levels of both
- test this by calling
ex1.say_something() ex2.say_something()
and reading
ex2.log