How to keep UTC time in logging while changing the TIME_ZONE settings?

余生颓废 提交于 2020-07-08 11:05:06

问题


I set the time zone in the settings.py file of my django project:

TIME_ZONE = 'US/Eastern'

and now my logs contain US/Eastern times.

I would like to keep an UTC time in my logs. Is that possible?


回答1:


Django uses Python's logging facilities, so there shouldn't be anything Django-specific here.

According to the logging documentation, setting logging.Formatter.converter = time.gmtime should make all logs output in UTC.

Alternatively, you can make your own Formatter class to use UTC:

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

And then configure it using the () key (documented here) in the dictconfig:

LOGGING = {
    'formatters': {
        'utc': { 
            '()': 'my.package.UtcFormatter',
            'format': '...',
            'datefmt': '...',
        }
    }
}


来源:https://stackoverflow.com/questions/26435764/how-to-keep-utc-time-in-logging-while-changing-the-time-zone-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!