Setting up logging mechanism in Django
Coming from a Java world where projects and libraries without logging are unheard, it was a big surprise to see that all django apps that I have downloaded so far do not include logging, even though Python has a very good support for logging, it was inspired by the log4j. For a reason that I do not know they choose not to log, I suppose it is a kind of situation where everyone else knows but me!
So as a java developer used to work with a lot of logging I decided to put in place a logging mechanism for my django project and fortunately python has great support for that:
1. create a logging.conf file for the logging options
2. configuring the logging module
3. using the logger in my modules
So here is my simple set up:
1. create a logging.conf file for the logging options with the following content:
[loggers]
keys=root,core_view_logger
[handlers]
keys=consoleHandler,core_view_handler
[formatters]
keys=simpleFormatter
[logger_root]
level=NOTSET
handlers=consoleHandler
[logger_core_view_logger]
level=DEBUG
handlers=core_view_handler
qualname=core_view_logger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_core_view_handler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=('logs/core_logger.log', 'a', 1000000, 4)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
2. configuring the logging module in the settings.py
import logging import logging.config LOGGING_CONFIG = 'logging.conf' # logging configuration file logging.config.fileConfig(LOGGING_CONFIG)
3.use the logger in your modules
import logging
logger = logging.getLogger('core_view_logger');
def doSomething(request):
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('Yes it is so simple :)')
That’s all folks!
But of course this is a simple set up and you can do more much more:
- Logging to multiple destinations
- Adding contextual information to the output
- Send and receive logging information across network
- Send logging information through email
Check the python official documentation for all the options http://docs.python.org/library/logging.html
Enjoy!
2 Comments
Jump to comment form | comment rss [?] | trackback uri [?]