繁体   English   中英

Python 在同一条消息中记录多个时区

[英]Python Logging log multiple timezone in same message

我有一个这样的日志格式化程序:

formatter = logging.Formatter('%(asctime)s \t [ %(asctime)s ] > %(message)s')

当它记录日志时,结果如下:

2020-08-10 22:21:16,173 [ 2020-08-10 22:21:16,173 ] > Something

但是,我不想让两个时间都在同一个时区,而是希望其中一个在另一个时区。 例如:

2020-08-10 22:21:16,173 [ 2020-08-10 18:21:16,173 ] > Something

我试过logging.Formatter.converter = time.gmtime ,但它将两个时间都转换为同一个时区。

据我在logging package 代码中看到的,一次只能使用一个转换器。 但是,您可以继承Formatter class 并覆盖formatTime方法以使用两个转换器。 生成的时间字符串应连接并返回。

formatTime文档说:

可以在格式化程序中重写此方法以提供任何特定要求,但基本行为如下:如果指定了 datefmt(字符串),则与 time.strftime() 一起使用以格式化记录的创建时间。

像这样的东西(我没有运行它):

def formatTime(self, record, datefmt=None):
    ct_local = time.localtime(record.created)
    ct_gmt =  time.gmtime(record.created)
    if datefmt:
        s = time.strftime(datefmt, ct_local) + '\t[' + time.strftime(datefmt, ct_gmt) + ']'
    else:
        t_local = time.strftime(self.default_time_format, ct_local)
        t_gmt = time.strftime(self.default_time_format, ct_gmt)
        s = self.default_msec_format % (t_local, record.msecs) + '\t[' + self.default_msec_format % (t_gmt, record.msecs) + ']' 
    return s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM