1

I have a config file config.ini as follows,

[loggers]
keys=root

[handlers]
keys=consoleHandler

[formatters]
keys=sampleFormatter

[logger_root]
level=INFO
handlers=consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=sampleFormatter
args=(sys.stderr,)

[formatter_sampleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

which I'm reading from my Python script as follows:

import logging

logging.config.fileConfig(fname="config.ini", disable_existing_loggers=False)

Now, I want to send this format read from the above file as a dictionary. So I use configparser to read this file and then convert to a dictionary as follows,

import configparser

parser = configparser.RawConfigParser()
parser.read(filenames="config.ini")
conf_dict = {section: dict(parser.items(section)) for section in parser.sections()}

Then, I learned that logging module's dictConfig requires the key version, so I add it as follows,

conf_dict["version"] = 1

Then, I try to read this dictionary into dictConfig as follows,

logging.config.dictConfig(config_dict)

However, this results in the following error,

  File "run.py", line 41, in load
    logging.config.dictConfig(config_dict)
  File "/python3.7/logging/config.py", line 799, in dictConfig
  File "/python3.7/logging/config.py", line 545, in configure
ValueError: Unable to configure formatter 'keys'

This seems to indicate that the two utilities of the logging module, fileConfig and dictConfig, accept two different formats. Is there a way to translate between these two formats? If so, how?

Saurabh
  • 163
  • 9

2 Answers2

0

No, there is no parser in the standard library that'll take an ini file and spit out a dictConfig compatible dictionary. You will have to create your own json file format to populate your dictionary.

You can find a good JSON file example here.

Subhash
  • 3,121
  • 1
  • 19
  • 25
0

As of Python 3.7 the two (dictConfig and fileConfig) cannot be expressed equivalently. For example, the "args" key can only be provided with the fileConfig. It will be ignored when provided with dictConfig.

As a side note, I came across this when trying to specify "args" for a dictConfig so that I could specify a file path that uses environment variables for a FileHandler.

Reference: config.py

_install_handlers - looks for the args key to evaluate it

configure_handler - does not look for the args key in the dict

Joe
  • 418
  • 4
  • 12
  • This is misleading. It's true that the dict config format doesn't support an `args` key for passing positional parameters, but all parameters can be passed as keywords (e.g. with `StreamHandler`, instead of trying to do `"args": (sys.stdout,)` (which won't work), it's `"stream": sys.stdout`. – mikenerone Sep 30 '22 at 17:29