3

I have named my Python loggers following the practice described in Naming Python loggers

Everything works fine if I use basicConfig(). But now I'm trying to use a configuration file and dictConfig() to configure the loggers at runtime.

The docs at http://docs.python.org/2/library/logging.config.html#dictionary-schema-details seem to say that I can have a "root" key in my dictionary that configures the root logger. But if I configure only this logger, I don't get any output.

Here's what I have:

logging_config.yaml

version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(pathname)s:%(lineno)s - %(message)s'
    datefmt: '%Y%m%d %H:%M:%S'

handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
  file:
    class: logging.FileHandler
    level: DEBUG
    formatter: simple
    filename: 'test.log'
    mode: "w"

# If I explicitly define a logger for __main__, it works
#loggers: 
#  __main__:
#    level: DEBUG
#    handlers: [console, file]
root:
  level: DEBUG
  handlers: [console, file]

test_log.py

import logging
logger = logging.getLogger(__name__)
import logging.config
import yaml

if __name__ == "__main__":
    log_config = yaml.load(open("logging_config.yaml", "r"))
    logging.config.dictConfig(log_config)
    #logging.basicConfig() #This works, but dictConfig doesn't
    logger.critical("OH HAI")
    logging.shutdown()

Why doesn't this produce any logging output, and what's the proper way to fix it?

Community
  • 1
  • 1
Thomas Johnson
  • 10,776
  • 18
  • 60
  • 98

1 Answers1

2

The reason is that you haven't specified disable_existing_loggers: false in your YAML, and the __main__ logger already exists at the time dictConfig is called. So that logger is disabled (because it isn't explicitly named in the configuration - if it is named, then it's not disabled).

Just add that line to your YAML:

version: 1
disable_existing_loggers: false
formatters:
  simple:
  ...
Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191