Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 375
yoozer8 Avatar asked Oct 23 '25 04:10

yoozer8


1 Answers

By default, the dictConfig method disables all the existing loggers.

You can change this behavior by adding disable_existing_loggers key with false value to logging-config.json.

{
  
  "logging": {
    "version": 1,
    "disable_existing_loggers": false,
    ...
  }
}
like image 159
napuzba Avatar answered Oct 25 '25 16:10

napuzba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!