简体   繁体   中英

Basic logging dictConfig in Python

NOTE I'm aware of this answer but that doesn't work for me, I am hoping for a complete, self-contained working example.

I'm trying to replace logging.basicConfig with dictConfig in Python (2.7)

My understanding is basicConfig simply sets up the root logger: so I'm attempting to do the same with the dictConfig . That is, set up the root logger with a handler, and then all the loggers in my application will propagate up the root logger.

What's missing from the following snippet? The behaviour is the log file is created, but no output makes it. (I've tried various combos of setting levels, it doesn't appear to help)

import logging
log_dict = {
    'loggers': {
        'root': {
            'handlers': ['file_handler']
        }
    },
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file_handler': {
            'filename': 'c:/mylogfile.log',
            'class': 'logging.FileHandler'
        }
    }
}

logging.config.dictConfig(log_dict)
logging.info('THIS IS A TEST')
logging.shutdown()
exit()

There are a couple of things wrong with your posted configuration:

  1. A logger with a name of 'root' is not the root logger. The root logger has a name of '' and is in general better configured using a 'root' entry outside the 'loggers' configuration, as described in this part of the logging documentation:

loggers - the corresponding value will be ...

...

root - this will be the configuration for the root logger. ...

  1. You haven't specified a logging level, so it remains at the default level of WARNING , which means that info() messages won't get shown.

The following code works perfectly for me:

import logging
import logging.config

log_dict = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'INFO',
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
        },
        'file_handler': {
            'level': 'INFO',
            'filename': '/tmp/mylogfile.log',
            'class': 'logging.FileHandler',
            'formatter': 'standard'
        }
    },
    'loggers': {
        '': {
            'handlers': ['file_handler'],
            'level': 'INFO',
            'propagate': True
        },
    }
}
logging.config.dictConfig(log_dict)
logging.info("test")

And indeed, it's based on the answer mentioned above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM