Skip to content

Instantly share code, notes, and snippets.

@vsajip
Created February 9, 2012 20:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vsajip/1782815 to your computer and use it in GitHub Desktop.
Save vsajip/1782815 to your computer and use it in GitHub Desktop.
Example of logging formatter factory usage with fileConfig()
import logging
class CustomFormatter(logging.Formatter):
def __init__(self, default):
self.default = default
def format(self, record):
if record.levelno in (logging.WARNING,
logging.ERROR,
logging.CRITICAL):
record.msg = '[%s] %s' % (record.levelname, record.msg)
return self.default.format(record)
def factory(fmt, datefmt):
default = logging.Formatter(fmt, datefmt)
return CustomFormatter(default)
from io import StringIO
import logging
import logging.config
CONFIG = u'''
[loggers]
keys=root
[handlers]
keys=console
[handler_console]
class=logging.StreamHandler
args=(sys.stderr,)
formatter=custom
[formatters]
keys=custom
[logger_root]
level=DEBUG
handlers=console
[formatter_custom]
format=%(asctime)s %(message)s
datefmt=%X
class=custfmt.factory
'''
cfg = StringIO(CONFIG)
logging.config.fileConfig(cfg)
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')
20:17:59 debug message
20:17:59 info message
20:17:59 [WARNING] warning message
20:17:59 [ERROR] error message
20:17:59 [CRITICAL] critical message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment