如何在更改TIME_ZONE设置的同时保持UTC时间记录? [英] How to keep UTC time in logging while changing the TIME_ZONE settings?

查看:53
本文介绍了如何在更改TIME_ZONE设置的同时保持UTC时间记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在django项目的 settings.py 文件中设置了时区:

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

TIME_ZONE ='美国/东部'

现在我的日志包含美国/东部时间.

and now my logs contain US/Eastern times.

我想在日志中保留UTC时间.有可能吗?

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

推荐答案

Django使用Python的日志记录工具,因此此处不应该包含Django专有的任何内容.

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

根据日志记录文档,将 logging.Formatter.converter = time.gmtime 应该将所有日志输出为UTC.

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

或者,您可以创建自己的 Formatter 类以使用UTC:

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

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

,然后使用()键(此处)在dictconfig中:

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

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

这篇关于如何在更改TIME_ZONE设置的同时保持UTC时间记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆