Python日志记录模块发出错误的时区信息 [英] Python logging module emits wrong timezone information
问题描述
我遇到了Python 2.7日志记录模块的问题.我的系统是Ubuntu 14.04 64bit,我住在意大利(目前是UTC + 1,没有夏令时);系统已正确配置为这样.
I'm running into an issue with Python 2.7 logging module. My system is Ubuntu 14.04 64bit, and I live in Italy (currently UTC+1, no daylight saving); the system is properly configured as such.
我想在当前时区发出日志行,并填写正确的时区偏移信息.
请考虑以下代码段:
#!/usr/bin/env python
import sys
print sys.version_info
import commands
print "System time: %s" % commands.getoutput("date --rfc-3339=seconds")
import logging
import datetime
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout,
format="%(asctime)s:" + logging.BASIC_FORMAT,
datefmt="%Y-%m-%dT%H:%M:%S%z")
logger = logging.getLogger()
logger.info("Something happened")
产生以下结果:
sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0)
System time: 2015-01-09 11:21:44+01:00
2015-01-09T11:21:44+0000:INFO:root:Something happened
因此,系统知道正确的时间和偏移量,而Python似乎弄错了时间.
So, the system knows the proper time AND offset, while Python seems to get the time wrong.
在datetime文档中,据说对于strftime中的%z,结果为"UTC偏移量,格式为+ HHMM或-HHMM(如果对象是天真对象,则为空字符串)".
In datetime docs, it is said that for %z in strftime the result is"UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive)".
因此,我期望获得以下任一结果:
So, I would have expected either of the following results:
- 日志记录模块要登录UTC,所以我会得到类似10:21.44和+0000偏移量的信息;
- 日志记录模块要登录本地时间,所以我会得到类似11:21:44和+01000偏移量的信息;
- 日志记录模块提供了朴素的datetime对象,我们完全没有获得偏移量.
相反,在这里我似乎得到了不可预测的-显然是错误的-结果.这是怎么回事?是否可以配置日志记录模块以执行我想要的操作而不会覆盖logging.Formatter对象的转换器功能(当然,我可以在其中做任何我想做的事,但这对我来说显然是个错误)?
On the contrary, here I seem to get an unpredictable - and plainly wrong - result. What's up? Is it possible to configure the logging module to do what I want WITHOUT overriding the converter function of logging.Formatter objects (where, of course, I can do whatever I like, but this looks plainly a bug to me)?
推荐答案
logging
使用不在时间元组中存储时区的time
模块,与datetime.strftime()
不同,time.strftime()
不支持%z
在Python 2上.您可以覆盖Formatter.formatTime()
方法,以使用时区感知日期时间对象作为建议使用@dmg 代替:>
logging
uses time
module that doesn't store timezone in a time tuple and time.strftime()
unlike datetime.strftime()
doesn't support %z
on Python 2. You could override Formatter.formatTime()
method to use timezone-aware datetime objects as @dmg suggested instead:
#!/usr/bin/env python
import logging
from datetime import datetime
import tzlocal # $ pip install tzlocal
def posix2local(timestamp, tz=tzlocal.get_localzone()):
"""Seconds since the epoch -> local time as an aware datetime object."""
return datetime.fromtimestamp(timestamp, tz)
class Formatter(logging.Formatter):
def converter(self, timestamp):
return posix2local(timestamp)
def formatTime(self, record, datefmt=None):
dt = self.converter(record.created)
if datefmt:
s = dt.strftime(datefmt)
else:
t = dt.strftime(self.default_time_format)
s = self.default_msec_format % (t, record.msecs)
return s
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(Formatter("%(asctime)s %(message)s", "%Y-%m-%dT%H:%M:%S%z"))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.info('something happened')
输出
2015-01-09T18:30:54+0100 something happened
这篇关于Python日志记录模块发出错误的时区信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!