How to configure the ‘logging’ module using dictionaries in Python 2.6
August 21, 2011 Comments
The logging.config module was updated in Python 2.7 and included a function called dictConfig() which takes a dictionary as an argument used to configure the logging module.
I wanted to use this in my new project so I can keep all my configurations/settings in one Python file but we’re not ready to upgrade to Python 2.7 just yet. The good news is you can just get the dictconfig module on its own and add it to your project. I actually just took it from the Django 1.3 package and put it in a package within the project I’m working on.
Here’s a sample configuration/usage for the ‘root’ logger:
Configuration:
LOG_SETTINGS = { 'version': 1, 'root': { 'level': 'NOTSET', 'handlers': ['console', 'file', 'smtp', 'mongodb'], }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'detailed', 'stream': 'ext://sys.stdout', }, 'file': { 'class': 'logging.handlers.RotatingFileHandler', 'level': 'INFO', 'formatter': 'detailed', 'filename': 'logs/MyProject.log', 'mode': 'a', 'maxBytes': 10485760, 'backupCount': 5, }, 'smtp': { 'class': 'logging.handlers.SMTPHandler', 'level': 'ERROR', 'formatter': 'email', 'mailhost': 'localhost', 'fromaddr': 'alerts@calazan.com', 'toaddrs': ['admin@calazan.com', 'support@calazan.com'], 'subject': '[My Project] Error encountered.', }, 'mongodb': { 'class': 'log4mongo.handlers.MongoHandler', 'level': 'DEBUG', 'host': 'localhost', 'port': 27017, 'database_name': 'myproject', 'collection': 'logs', 'username': 'logger', 'password': 'password', }, }, 'formatters': { 'detailed': { 'format': '%(asctime)s %(module)-17s line:%(lineno)-4d ' \ '%(levelname)-8s %(message)s', }, 'email': { 'format': 'Timestamp: %(asctime)s\nModule: %(module)s\n' \ 'Line: %(lineno)d\nMessage: %(message)s', }, }, }
Usage:
import logging import dictconfig from settings import LOG_SETTINGS dictconfig.dictConfig(LOG_SETTINGS) logging.debug('This is a debug message!') logging.info('This is an info message!') logging.error('This is an error message!')
Tags: howto, python, tech, software development