logging 1 2 3

levels, attributes references

The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

  1. Loggers expose the interface that application code directly uses.
  2. Handlers send the log records (created by loggers) to the appropriate destination.
  3. Filters provide a finer grained facility for determining which log records to output.
  4. Formatters specify the layout of log records in the final output.

Step 0: Project structure

code/
├── main.py
├── config
├   └── logging.conf
└── logs
    └── app.log

Step 1: Create file logging.conf

[loggers]
keys=root

[handlers]
keys=consoleHandler,fileHandler

[formatters]
keys=formatter

[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stdout,)

[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=formatter
args = ('logs/app.log','a')

[formatter_formatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

Step 2: Load config and create logger

In main.py

import logging.config

# load logging config
logging.config.fileConfig('config/logging.conf')

Step 3: In your application code

logging.getLogger().debug('debug message')
logging.getLogger().info('info message')
logging.getLogger().warn('warn message')
logging.getLogger().error('error message')
logging.getLogger().critical('critical message')

More Resources