如何在Python日志记录中更改时区? [英] How to Change the time zone in Python logging?

查看:960
本文介绍了如何在Python日志记录中更改时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改日志文件中的时间戳,使其反映我当前的时区,以便我可以更快的速度调试错误,

I would like to change the timestamp in the log file so that it reflects my current time zone so that i can debug errors at a faster rate,

是吗可以更改日志文件中的时区吗?

is it possible that i can change the time zone in the log file ?

当前我的配置是:

logging.basicConfig(filename='audit.log',
                filemode='w',
                level=logging.INFO,
                format='%(asctime)s %(message)s',
                datefmt='%m/%d/%Y %I:%M:%S %p')


推荐答案

如何记录时区



%Z 来自 strftime 格式

Windows

>>> import logging
>>> logging.basicConfig(format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p %Z")
>>> logging.error('test')
11/03/2017 02:29:54 PM Mountain Daylight Time test

Linux

>>> import logging
>>> logging.basicConfig(format="%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p %Z")
>>> logging.error('test')
11/03/2017 02:30:50 PM MDT test

如果问题是


如何登录与服务器本地时间不同的时区? / strong>

How do I log in a different timezone than the local time on the server?

部分答案是 logging.Formatter.converter ,但是,您必须懂得天真并意识到 datetime 对象。除非您要编写自己的时区模块,否则我强烈建议使用 pytz 库( pip install pytz )。 Python 3包含UTC和UTC偏移时区,但是对于夏时制或其他偏移,您必须实施一些规则,因此我建议使用pytz库,即使对于python 3也是如此。

part of the answer is logging.Formatter.converter, however, you have to understand naive and aware datetime objects. Unless you want to write your own timezone module, I highly suggest the pytz library (pip install pytz). Python 3 includes a UTC and UTC offset timezone, but there's rules you'll have to implement for daylight savings or other offsets, so I would suggest the pytz library, even for python 3.

例如,

>>> import datetime
>>> utc_now = datetime.datetime.utcnow()
>>> utc_now.isoformat()
'2019-05-21T02:30:09.422638'
>>> utc_now.tzinfo
(None)

如果我将时区应用于此datetime对象,则时间不会改变(或会针对python 3.7ish发出 ValueError )。

If I apply a timezone to this datetime object, the time won't change (or will issue a ValueError for < python 3.7ish).

>>> mst_now = utc_now.astimezone(pytz.timezone('America/Denver'))
>>> mst_now.isoformat()
'2019-05-21T02:30:09.422638-06:00'
>>> utc_now.isoformat()
'2019-05-21T02:30:09.422638'

但是,则改为

>>> import pytz
>>> utc_now = datetime.datetime.now(tz=pytz.timezone('UTC'))
>>> utc_now.tzinfo
<UTC>

现在我们可以创建正确翻译的 datetime 对象

now we can create a properly translated datetime object in whatever timezone we wish

>>> mst_now = utc_now.astimezone(pytz.timezone('America/Denver'))
>>> mst_now.isoformat()
'2019-05-20T20:31:44.913939-06:00'

啊哈!现在将其应用于日志记录模块。

Aha! Now to apply this to the logging module.

LogRecord.created 属性设置为创建 LogRecord 的时间(由 time.time() ),从 time 模块。这将返回一个时间戳记(<< a href = https://en.wikipedia.org/wiki/Unix_time rel = nofollow noreferrer>自该纪元以来的秒数)。您可以对给定的时区进行自己的翻译,但是我还是建议通过覆盖转换器来 pytz

The LogRecord.created attribute is set to the time when the LogRecord was created (as returned by time.time()), from the time module. This returns a timestamp (seconds since the epoch). You can do your own translation to a given timezone, but again, I suggest pytz, by overriding the converter.

import datetime
import logging
import pytz

class Formatter(logging.Formatter):
    """override logging.Formatter to use an aware datetime object"""
    def converter(self, timestamp):
        dt = datetime.datetime.fromtimestamp(timestamp)
        tzinfo = pytz.timezone('America/Denver')
        return tzinfo.localize(dt)

    def formatTime(self, record, datefmt=None):
        dt = self.converter(record.created)
        if datefmt:
            s = dt.strftime(datefmt)
        else:
            try:
                s = dt.isoformat(timespec='milliseconds')
            except TypeError:
                s = dt.isoformat()
        return s

Python 3.5、2.7

Python 3.5, 2.7

>>> logger = logging.root
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(Formatter("%(asctime)s %(message)s"))
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.DEBUG)
>>> logger.debug('test')
2019-05-20T22:25:10.758782-06:00 test

Python 3.7

Python 3.7

>>> logger = logging.root
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(Formatter("%(asctime)s %(message)s"))
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.DEBUG)
>>> logger.debug('test')
2019-05-20T22:29:21.678-06:00 test

用pytz定义的posix时区用 America / Anchorage 代替 America / Denver

>>> next(_ for _ in pytz.common_timezones if 'Alaska' in _)
'US/Alaska'

美国/阿拉斯加已弃用

>>> [_ for _ in pytz.all_timezones if 'Anchorage' in _]
['America/Anchorage']



本地



如果您遇到此问题和答案,以查找如何记录本地时区,则可以使用 tzlocal pip install tzlocal )并替换

        tzinfo = pytz.timezone('America/Denver')

with

        tzinfo = tzlocal.get_localzone()

现在它将在运行脚本的任何服务器上运行,并且时区为服务器。

Now it will work on whatever server runs the script, with the timezone on the server.

我应该添加一个,具体取决于应用程序,登录本地时区可以每年产生两次歧义,其中跳过凌晨2点或重复凌晨1点,可能还有其他情况。

I should add, depending on the application, logging in local time zones can create ambiguity twice a year, where 2 AM is skipped or 1 AM repeats, and possibly others.

这篇关于如何在Python日志记录中更改时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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