这是日期所需的表示形式:
>>> tz = pytz.timezone('US/Central')
>>> datefmt = '%Y-%m-%d %H:%M:%S.%f%z(%Z)'
>>> datetime.now(tz).strftime(datefmt)
'2017-04-27 15:09:59.606921-0500(CDT)'
这就是记录的方式(Linux上的Python 3.6.0(:
>>> logrecord_format = '%(asctime)s %(levelname)s %(message)s'
>>> logging.basicConfig(format=logrecord_format, datefmt=datefmt)
>>> logging.error('ruh-roh!')
2017-04-27 15:10:35.%f-0500(CDT) ERROR ruh-roh!
它不能正确填充微秒。我已经尝试将logrecord_format
更改为其他几件事,但是我无法弄清楚 - 如何以正确的方式配置记录器以显示微秒和时区以完全匹配strftime
输出?
编辑:我可以以偏移为毫秒,即2017-04-27 15:09:59,606-0500(CDT)
。那可能吗?logging
提供了%(msecs)03d
指令,但我似乎无法在毫秒之后出现时区的偏移量。
个人,而不是将时区集成到日期格式中,而是将其直接添加到记录的消息格式中。通常,在程序执行过程中,时区不应更改。
import logging
import time
tz = time.strftime('%z')
fmt = '%(asctime)s' + tz + ' %(levelname)s %(message)s'
logging.basicConfig(format=fmt)
logging.error("This is an error message.")
# 2017-07-28 19:34:53,336+0200 ERROR This is an error message.
比接受的答案更正式,要获得微秒,您需要使用datetime
而不是time
进行字符串格式。
import logging
import pytz
from datetime import datetime
class TZAwareFormatter(logging.Formatter):
"""
A timezone-aware logging formatter.
By default, Python's `logging` module uses the `time` module for conversion
of timestamps to time tuples, which doesn't support %f for microsecond formatting
"""
def __init__(self, tz, *args, **kwargs):
super().__init__(*args, **kwargs)
self.tz = tz
def converter(self, timestamp):
return datetime.fromtimestamp(timestamp, self.tz)
def formatTime(self, record, datefmt=None):
dt = self.converter(record.created)
if datefmt:
s = dt.strftime(datefmt)
else:
s = dt.strftime(self.default_time_format)
if self.default_msec_format:
s = self.default_msec_format % (s, record.msecs)
return s
以及如何使用它:
# Update the logging root handler to use correct Formatter
logging.basicConfig()
root_logger = logging.getLogger()
root_handler = root_logger.handlers[0]
root_handler.setFormatter(
TZAwareFormatter(
tz=pytz.timezone('US/Central'),
fmt='%(asctime)s %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S.%f%z (%Z)'
)
)
logging.error('uh-oh!')