How to Change the time zone in Python logging?

前端 未结 7 1395
耶瑟儿~
耶瑟儿~ 2021-01-31 18:30

I would like to change the timestamp in the log file so that it reflects my current time zone so that i can debug errors at a faster rate,

is it possible that i can cha

7条回答
  •  忘了有多久
    2021-01-31 19:04

    An alternative solution if you want to use logging configuration function:

    import pytz
    import logging
    import logging.config
    from datetime import datetime
    
    tz = pytz.timezone('Asia/Tokyo')
    
    class TokyoFormatter(logging.Formatter):
        converter = lambda *args: datetime.now(tz).timetuple()
    
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'beijing': {
                '()': TokyoFormatter,
                'format': '%(asctime)s %(levelname)s: %(message)s',
                'datefmt': '%Y-%m-%d %H:%M:%S'
            },
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'formatter': 'beijing'
            },
        },
        'loggers': {
            'foo': {
                'handlers': ['console'],
                'level': 'INFO'
            },
        }
    }
    
    logging.config.dictConfig(LOGGING)
    logger = logging.getLogger('foo')
    logger.info('Just a test.')
    

    For more details, please refer to Customizing handlers with dictConfig().

提交回复
热议问题