Search code examples
pythonloggingyaml

Python Logging Config


I'm trying a simple setup with python logging using the json format. I've copied some config data from the logging config tutorial but when importing it I get:

(env) pi@omni-demo:~/omni-reader $ python
Python 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging
>>> import logging.config
>>> logging.config.dictConfig('logging.conf')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.11/logging/config.py", line 812, in dictConfig
    dictConfigClass(config).configure()
    ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/logging/config.py", line 374, in __init__
    self.config = ConvertingDict(config)
                  ^^^^^^^^^^^^^^^^^^^^^^
ValueError: dictionary update sequence element #0 has length 1; 2 is required

The logging.conf file is:

version: 1
formatters:
    simple:
        format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
    console:
        class: logging.StreamHandler
        level: ERROR
        formatter: simple
        stream: ext://sys.stdout
loggers:
    root:
        level: ERROR
        handlers: [console]

The error is non descriptive and I just can't figure out what is the problem as the example is very simple. Can anyone assist please?

Regards,

Neil


Solution

  • Load the configuration from logging.conf using your YAML library of choice, and pass the resulting dictionary to dictConfig() like in this example:

    import logging.config
    import yaml
    
    with open('logging.conf') as f:
        conf = yaml.safe_load(f)
    logging.config.dictConfig(conf)