Friday, 8 January 2021

Named logger not writing when using dictConfig

When I try to write logs using named loggers for each module, I expect that the logs will propagate to the root logger if there are no handlers configured specifically for the named logger. This works fine when I use basicConfig, but when I use dictConfig, the log messages from the named logger get discarded.

How do I get the named logger to properly write out the log messages?

foo.py:

import logging

logger = logging.getLogger('foo')


def doFoo(text):
    logger.debug(text)
    logger.info(text)
    logger.warn(text)
    logger.error(text)

main.py:

import json
import logging.config
import foo

# logging.basicConfig(level=logging.DEBUG) # works as expected with this
with open('logging-config.json') as f:
    config = json.load(f)
logging.config.dictConfig(config['logging'])
logging.info('starting')
foo.doFoo('this is a test')

logging-config.json:

{
  "logging": {
    "version": 1,
    "formatters": {
      "standard": {
        "class": "logging.Formatter",
        "datefmt": "%Y-%m-%d %H:%M:%S",
        "format": "%(asctime)s %(name)s %(levelname)s: %(message)s"
      }
    },
    "handlers": {
      "stdout": {
        "class": "logging.StreamHandler",
        "level": "INFO",
        "formatter": "standard",
        "stream": "ext://sys.stdout"
      }
    },
    "root": {
        "level": "INFO",
        "handlers": ["stdout"]
    }
  }
}

When I run with the dictConfig, I only see root INFO: starting.

When I run with basicConfig, I see all the log messages.

I know that the named logger is created (via import execution of the module) before the call to configure logging, but from some testing I've seen that a logger will only discard log messages if it is used before logging is configured (and will emit a message "No handlers could be found for logger {name}").

What do I need to do to get the named loggers to work?



from Named logger not writing when using dictConfig

No comments:

Post a Comment