Allow a name for the root logger so that TOML can be used to store a logging config

TOML is becoming common in the Python ecosystem. pyproject.toml is the packaging standard and 3.11 gets the tomllib parser in the standard library.

Storing a logging configuration in a toml file means occasionally storing a configuration for the root logger, normally specified as logging_config["loggers"][""]. However, this configuration cannot be written to a toml file since the specification does not allow empty or white-space-only fields. This can be worked around by using JSON or by providing a sentinel value (eg, _root_) and handling that value in application code. It would be easier if the root logger could optionally be specified by name, such as RootLogger or _root_.

Interestingly, if you structure your toml file correctly, you can specify the empty field name, but it seems this is a bug, not a feature, and is not reliable through load/dump cycles:

>>> import toml
>>> from pprint import pprint

>>> config = toml.loads("""
                        [loggers]
                        '' = {level='NOTSET', handlers=[]}
                        'logger_1' = {level='ERROR', handlers=['handler_1']}
                        """)

>>> pprint(config)
{'loggers': {'': {'handlers': [], 'level': 'NOTSET'},
             'logger_1': {'handlers': ['handler_1'], 'level': 'ERROR'}}}

>>> toml_config = toml.dumps(config)

>>> print(toml_config)
[loggers.""]
level = "NOTSET"
handlers = []

[loggers.logger_1]
level = "ERROR"
handlers = [ "handler_1",]

>>> config_from_dump = toml.loads(toml_config)
[...]
TomlDecodeError: Can't have a keygroup with an empty name (line 4 column 1 char 23)

What exactly is a bug?

Per the TOML specification, an empty (quoted) key is explicitly allowed.

The bug here is rather in the toml library when it fails to parse the [xxx.""] table header. I see that you already opened a bug report about it.

tomllib for example handles this correctly.

1 Like

Oh man. You are right about that. I had forgotten about filing the toml bug report and found myself dealing with this again and miss-remembering why it was an issue. I’m using py3.8 for deployment environment reasons so haven’t been able to test tomllib yet. Thanks for looking into it.

tomllib was basically the inclusion of tomli in the stdlib, so try that (or tomlkit if you need format-preserving roundtrips) if you’re on an older Python version.