Created
February 6, 2016 15:12
-
-
Save alanbriolat/d5ffe608b56c948533c6 to your computer and use it in GitHub Desktop.
disable_existing_loggers by default in Python logging's dictConfig() is horrible...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!