Python日志记录:如何设置GMT的时间

时间:2011-06-12 09:16:48

标签: python logging timezone

是否可以以及如何将记录时区设置为GMT?

(即格式中的%(asctime)s参数)

5 个答案:

答案 0 :(得分:54)

logging.Formatter.converter = time.gmtime

(记录在logging.Formatter.formatTime的文档字符串中)

答案 1 :(得分:6)

在Python 2.5中设置logging.Formatter.converter = time.gmtime对我来说无效。

所以我创建了一个子类,并使用它来代替logging.Formatter:

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

答案 2 :(得分:2)

来自python 3文档:

import time

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

https://docs.python.org/3/howto/logging-cookbook.html#formatting-times-using-utc-gmt-via-configuration

答案 3 :(得分:0)

我对这两个答案都有疑问。所以我刚刚更改了整个脚本的全局时区:

os.environ['TZ'] = 'Europe/London'
time.tzset()

答案 4 :(得分:0)

这是代码示例:

import logging, logging.handlers
import time

logit = logging.getLogger('logit')
handler = logging.handlers.RotatingFileHandler("file.log", maxBytes=20000, backupCount=5)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(levelname)8s: %(message)s')
handler.setFormatter(formatter)
logging.Formatter.converter = time.gmtime
logit.addHandler(handler)

logit.info("test log message")

输出:

2019-11-14 16:34:22,967     INFO: test log message