5

I am using dictConfig to setup logging. One of the requirements I have is to change the default converter of the formatter (I am using a single formatter simpleFormatter for all my handlers) to time.gmtime. This would be done like this:

formatter.converter = time.gmtime

If I had access to the formatter. But I don't, so I can not change the default converter. I can think of two ways of doing what I want:

  • pass the relevant parameter via dictConfig, in the formatters section (something like 'converter': 'ext://time.gmtime') But I think this extra parameter is not supported by dictConfig
  • get the formatter after doing a dictConfig and apply the configuration manually: formatter.converter = time.gmtime. I do not know how to get the formatter by name, or whether it is supported or if would be hacking around the logging.config module.

I have found neither examples, nor documentation, nor a way to implement this after taking a look at the source code of the logging module.

Has somebody managed to setup the formatter.converter using a dictConfig setup?

blueFast
  • 41,341
  • 63
  • 198
  • 344

1 Answers1

5

Here's an example of how to do it:

import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
   }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('Look out!')

When I run the above, I get:

2015-10-17 12:20:36,217 Look out!
2015-10-17 13:20:36,217 Look out!

The use of the '()' key for custom instantiations is documented here in the paragraph beginning All other keys ....

Vinay Sajip
  • 95,872
  • 14
  • 179
  • 191
  • It's not clear about `()` thing in `logging.config.DictConfigurator.configure_formatter`. Maybe you'd make it a constant with a good name, maybe: `FORMATTER_FACTORY='()'`. Thanks for link. – simno Apr 02 '18 at 08:18