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()
%%file ex1.py
import logging
logger = logging.getLogger(__name__)
def say_something():
logger.warning('this is a warning message')
### 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()
%%file ex2.py
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def say_something():
logger.info('this is an informative message')
### 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?
import yaml
import logging.config
ex2.logger.setLevel(logging.DEBUG)
ex2.say_something()
config_string = """
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: INFO
handlers: [console]
"""
config_dict = yaml.safe_load(config_string)
logging.config.dictConfig(config_dict)
# now the log level is set to ERROR
# so there should be no output from this logger
ex2.say_something()
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
config_string = """
version: 1
disable_existing_loggers: False
formatters:
simple:
format: '%(asctime)s | %(levelname)s | %(name)s | %(message)s'
handlers:
console:
class: logging.StreamHandler
formatter: simple
stream: ext://sys.stderr
root:
handlers: [console]
"""
config_dict = yaml.safe_load(config_string)
logging.config.dictConfig(config_dict)
ex1.say_something()
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
config_string = """
version: 1
disable_existing_loggers: False
formatters:
simple:
format: '%(asctime)s :: %(levelname)s :: Module %(module)s :: Line No %(lineno)s :: %(message)s'
handlers:
console:
class: logging.StreamHandler
formatter: simple
stream: ext://sys.stderr
root:
handlers: [console]
"""
config_dict = yaml.safe_load(config_string)
logging.config.dictConfig(config_dict)
ex1.say_something()
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
from pathlib import Path
config_string = """
version: 1
disable_existing_loggers: False
formatters:
simple:
format: '%(asctime)s :: %(levelname)s :: Module %(module)s :: Line No %(lineno)s :: %(message)s'
handlers:
console:
class: logging.StreamHandler
formatter: simple
stream: ext://sys.stderr
ex2:
class: logging.FileHandler
formatter: simple
filename: ex2.log
mode: 'w'
loggers:
ex2:
handlers: [ex2]
level: DEBUG
ex1:
level: DEBUG
root:
handlers: [console]
"""
config_dict = yaml.safe_load(config_string)
logging.config.dictConfig(config_dict)
ex1.say_something()
ex2.say_something()
print('ex2.log:', Path('ex2.log').read_text())
!dir