blueFast
blueFast

Reputation: 44501

How to reconfigure a logger formatter when using dictConfig

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:

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?

Upvotes: 8

Views: 4477

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99530

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 ....

Upvotes: 10

Related Questions