Python logging with dictConfig and using GMT / UTC zone time

Viewed 55

I'm trying to configure some logging across multiple modules within a package. These modules may be executed in different containers, possibly in different regions, so I wanted to explicitly use GMT / UTC time for logging.

When I'm reading about the Formatter class in logging, it indicates you can specify converter to use either local-time or GMT. I'd like to utilize this feature, in conjunction with dictConfig (or possibly fileConfig) to specify the configurations for the different modules, but the documentation is sparse with respect to this feature. Everything specified in the config is working, except for the timezone. The log always uses local time. I can include the '%z' formatting specification in datefmt to specify offset from GMT, but that breaks the .%(msecs)03d formatting.

Below is my code using a defined dictionary and dictConfig. Has anyone had any success specifying timezone in the config? is this possible?

import json
import logging
from logging.config import dictConfig
import time

DEFAULT_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(levelname)s : %(name)s : %(asctime)s.%(msecs)03d : %(message)s', 
            'datefmt': '%Y-%m-%d %H.%M.%S',
            'converter': time.gmtime # also fails with 'time.gmtime', 'gmtime'
        }
    },
    'handlers' : {
            'default': {
                'level': 'NOTSET', 
                'class': 'logging.StreamHandler',
                'formatter': 'standard',
            }
    }, 
    'loggers': {
            'TEST': { # logging from this module should be logged in DEBUG level
                'handlers' : ['default'], 
                'level': 'INFO', 
                'propagate': False,
            },
    },
    'root': {
            'level': 'INFO',
            'handlers': ['default']
    },
    'incremental': False
    }

if __name__ == '__main__':
    dictConfig(DEFAULT_CONFIG)
    logger = logging.getLogger('TEST')
    logger.debug('debug message') # this should not be displayed if level==INFO
    logger.info('info message')
    logger.warning('warning message')
    logger.error('error message')

Output:

INFO : TEST : 2022-07-07 17.20.13.434 : info message WARNING : TEST : 2022-07-07 17.20.13.435 : warning message ERROR : TEST : 2022-07-07 17.20.13.435 : error message

0 Answers
Related