Sunday, April 20, 2008

Python logger config thread safety

Yes, the python logger is thread safe, but don't configure it programmatically (i.e. not via config file). Adding handlers to a logger with getLogger().addHandler(handler) does just that - and it will add handlers ad infinitum, even if they are already added.

So if you want to set logger options, in say, a Django settings.py file:

import logging.config
logging.config.fileConfig("logging.conf")

Your logging.conf might look like this:

[loggers]
keys=root

[handlers]
keys=errhandler,filehandler

[formatters]
keys=formatter

[logger_root]
level=NOTSET
handlers=errhandler,filehandler
formatters=formatter

[handler_errhandler]
class=StreamHandler
level=NOTSET
formatter=formatter
args=(sys.stdout,)

[handler_filehandler]
class=handlers.RotatingFileHandler
level=NOTSET
formatter=formatter
args=("/var/log/django/my.log", "a", 1024*1024)

[formatter_formatter]
format=[%(asctime)s] - %(levelname)-8s - "%(message)s" (%(filename)s: %(funcName)s - %(lineno)s)
datefmt=%Y-%m-%d %a %H:%M:%S
class=logging.Formatter

Labels: , ,

0 Comments:

Post a Comment

<< Home