Skip to content

Instantly share code, notes, and snippets.

@alanbriolat
Created February 6, 2016 15:12
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanbriolat/d5ffe608b56c948533c6 to your computer and use it in GitHub Desktop.
Save alanbriolat/d5ffe608b56c948533c6 to your computer and use it in GitHub Desktop.
disable_existing_loggers by default in Python logging's dictConfig() is horrible...
import logging
import logging.config
# A logger that exists before configuration
log_a = logging.getLogger('a')
def f(name, x):
"""Test a logger."""
log = logging.getLogger(name)
log.debug('debug from %s: %s', name, x)
# These won't output anything, because logging isn't configured
f('a', 1)
f('b', 2)
def old():
"""Both existing and new loggers work."""
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(
'[%(asctime)s] (%(levelname).1s:%(name)s) %(message)s',
datefmt='%Y/%m/%d %H:%M:%S',
))
rootlogger = logging.getLogger('')
rootlogger.addHandler(handler)
rootlogger.setLevel(logging.DEBUG)
f('a', 3)
f('c', 4)
def broken():
"""Seemingly equivalent config, but only new loggers work."""
logging.config.dictConfig({
'version': 1,
'formatters': {
'default': {
'format': '[{asctime}] ({levelname[0]}:{name}) {message}',
#'format': '[%(asctime)s] (%(levelname).1s:%(name)s) %(message)s',
'datefmt': '%Y/%m/%d %H:%M:%S',
'style': '{',
},
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'default',
},
},
'root': {
'level': 'DEBUG',
'handlers': ['default'],
},
})
f('a', 5)
f('d', 6)
def fixed():
"""Override the obnoxious default, and now existing and new loggers work again."""
logging.config.dictConfig({
'version': 1,
'formatters': {
'default': {
'format': '[{asctime}] ({levelname[0]}:{name}) {message}',
#'format': '[%(asctime)s] (%(levelname).1s:%(name)s) %(message)s',
'datefmt': '%Y/%m/%d %H:%M:%S',
'style': '{',
},
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'default',
},
},
'root': {
'level': 'DEBUG',
'handlers': ['default'],
},
'disable_existing_loggers': False,
})
f('a', 7)
f('e', 8)
#old()
#broken()
fixed()
@AlexandrDragunkin
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment