Kempe
Kempe

Reputation: 367

python2.7: logging configuration with yaml

I'm trying to configure a logger from a yaml file. On docs.python.org I found an example of how to create a yaml file, and the file I created looks like this:

formatters:
    simpleFormater:
        format: '%(asctime)s - %(levelname)s: %(message)s'
        datefmt: '%Y/%m/%d %H:%M:%S'

handlers:
    console:
        class: logging.StreamHandler
        formatter: simpleFormater
        level: DEBUG
        stream: ext://sys.stdout
    file:
        class : logging.FileHandler
        formatter: simpleFormater
        level: WARNING
        filename: songinfo.log

loggers:
    clogger:
        level: DEBUG
        handlers: [console]
    flogger:
        level: WARNING
        handlers: [file]

root:
    level: DEBUG
    handlers: [console, file]

But I can't find an example of how to load the config. I saw something about loading it with:

logging.config.dictConfig(yaml.load(open('logging.conf', 'r')))

but that throws a "ValueError: dictionary doesn't specify a version"

So my question is: how do I load this to a logger in Python and how do I use clogger and flogger.

Upvotes: 18

Views: 10658

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81926

From reading the python documentation, we see that there is a required key in the configuration which says version.

You need a line in your configuration which says

version: 1

Or, you can do:

with open('logging.conf') as f:
    D = yaml.load(f)
    D.setdefault('version', 1)
    logging.config.dictConfig(D)

Upvotes: 17

Related Questions