Skip to content

Instantly share code, notes, and snippets.

@mw44118
Created March 6, 2013 17:55
Show Gist options
  • Save mw44118/5101479 to your computer and use it in GitHub Desktop.
Save mw44118/5101479 to your computer and use it in GitHub Desktop.
python logging.config.dictConfig vs using code
# vim: set expandtab ts=4 sw=4 filetype=python fileencoding=utf8:
"""
Is there something wrong with logging.dictConfig, or am I just using it
wrong?
Run like
$ python scratch.py code
and then
$ python scratch.py dict
and see how the logging output is different.
"""
import argparse
import logging
import logging.config
log1 = logging.getLogger('scratch')
def configure_logging_with_dictConfig():
d = {
'formatters': {
'consolefmt': {
'format': '%(asctime)s %(levelname)-10s %(process)-6d %(name)-24s %(lineno)-4d %(message)s'}},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'consolefmt',
'level': 'DEBUG'}},
'root': {
'handlers': ['console'],
'level': 'DEBUG'},
'version': 1}
logging.config.dictConfig(d)
def configure_logging_with_code():
# Set the logger to DEBUG.
logging.root.setLevel(logging.DEBUG)
# Now write a custom formatter, so that we get all those different
# things.
f = logging.Formatter(
'%(asctime)s '
'%(levelname)-10s '
'%(process)-6d '
'%(filename)-24s '
'%(lineno)-4d '
'%(message)s '
)
# Set up a stream handler for DEBUG stuff (and greater).
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
sh.setFormatter(f)
logging.root.addHandler(sh)
def set_up_arguments():
ap = argparse.ArgumentParser()
ap.add_argument('how_to_configure', choices=['code', 'dict'])
return ap.parse_args()
if __name__ == '__main__':
args = set_up_arguments()
if args.how_to_configure == 'code':
configure_logging_with_code()
elif args.how_to_configure == 'dict':
configure_logging_with_dictConfig()
log1.debug('debug from log1')
log2 = logging.getLogger('log2')
log2.debug('debug from log2')
print "log.root.level: {0}".format(log1.root.level)
print "log.root.handlers: {0}".format(log1.root.handlers)
print "log1.parent.level: {0}".format(log1.parent.level)
print "log1.parent.handlers: {0}".format(log1.parent.handlers)
print "log1.level: {0}".format(log1.level)
print "log1.handlers: {0}".format(log1.handlers)
print "log1.propagate: {0}".format(log1.propagate)
print "log1.getEffectiveLevel(): {0}".format(log1.getEffectiveLevel())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment