【问题标题】:Changing time format inside twisted matrix log改变扭曲矩阵日志中的时间格式
【发布时间】:2013-06-08 21:24:16
【问题描述】:

如何更改 TwistedMatrix 中使用的日志系统的时间格式?

我注意到 http://twistedmatrix.com/trac/browser/tags/releases/twisted-11.0.0/twisted/python/log.py#L389 应该允许更改 timeFormat,但它不起作用 对我来说,这是我执行的完整测试程序python myscript.py

from twisted.internet import endpoints, reactor

from twisted.python import log
from twisted.application.service import Application
from twisted.python.log import ILogObserver, FileLogObserver
from twisted.python.logfile import DailyLogFile

#[... here my definition of a ProxyFactory()...]

application = Application("myapp")
logfile = DailyLogFile("my.log", './')
flo = FileLogObserver(logfile)
flo.timeFormat = "%Y-%m-%d %H:%M:%S,%f%z"
application.setComponent(ILogObserver, flo.emit)

log.startLogging(logfile)
log.msg("this is a test")

endpoint = endpoints.serverFromString(reactor, portstr)
d = endpoint.listen(ProxyFactory())
d.addErrback(shutdown, reactor)
reactor.run()

没有得到预期的结果:“%Y-%m-%d %H:%M:%S,%f%z”(毫秒)

2013-06-12 17:08:07+0200 [-] Log opened.
2013-06-12 17:08:12+0200 [-] this is a test

我错过了什么?

还有:

  • 当我不需要文件时,我必须如何更改此时间格式 日志记录但仅 stderr 打印?

(其他参考:http://twistedmatrix.com/trac/ticket/3513

编辑:我试图重新表述我的两个问题。

所以从 JeanPaul 发布的答案中,我了解到我将事物和经典 python 文件与另一个 tac 文件混合在一起(在阅读 JeanPaul 之前我不知道)。顺便说一句,我在下面尝试了这个,但仍然没有得到我需要的毫秒数:

(这次我要启动twistd -noy my.tac

from twisted.application.service import Application
from twisted.python.log import ILogObserver, FileLogObserver
from twisted.python.logfile import DailyLogFile

application = Application("myapp")
logfile = DailyLogFile("my.log", "./")
flo = FileLogObserver(logfile)
flo.timeFormat = "%Y-%m-%d %H:%M:%S,%f %z"
application.setComponent(ILogObserver, flo.emit)

然后得到:

2013-06-13 17:23:23,%f+0000 [-] Log opened.
2013-06-13 17:23:23,%f+0000 [-] using set_wakeup_fd
2013-06-13 17:23:23,%f+0000 [-] twistd 12.0.0 (/usr/bin/python 2.7.3) starting up.
2013-06-13 17:23:23,%f+0000 [-] reactor class: twisted.internet.pollreactor.PollReactor.
2013-06-13 17:23:30,%f+0000 [-] Received SIGINT, shutting down.
2013-06-13 17:23:30,%f+0000 [-] Main loop terminated.
2013-06-13 17:23:30,%f+0000 [-] Server Shut Down.

你可以看到我是否模仿 @http://twistedmatrix.com/trac/browser/trunk/twisted/python/log.py#L351 所做的事情,见第 367 行,python 和时间给了我这个毫秒。还要注意 %Z 是错误的,它应该是 +0200,但是当我需要毫秒时,我将能够忍受它......

Python 2.7.3 (default, Jan  2 2013, 13:56:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> datetime.datetime.now().strftime("%H:%M:%S.%f")
'17:28:06.566135'
>>> import time
>>> when = time.time()
>>> import datetime
>>> datetime.datetime.fromtimestamp(when).strftime("%Y-%m-%d %H:%M:%S,%f%z")
'2013-06-13 17:33:20,535350'
>>> import twisted
>>> twisted.version
Version('twisted', 12, 0, 0)

【问题讨论】:

    标签: python logging twisted


    【解决方案1】:

    您在此处对日志系统执行了几项不同的操作。您要求twistd 使用flo.emit 作为日志观察者。这将在twistd 加载此tac 文件 中定义的application 后生效。然后,您手动初始化日志系统以使用logfile 并立即记录一条消息。由于这是tac 文件的一部分,twistd 尚未完成对application 的加载,因此它尚未应用您使用ILogObserver 指定的日志记录配置。相反,日志事件由您使用startLogging - logfile 设置的日志观察器处理,它对自定义时间戳格式一无所知。

    删除startLogging 调用,您应该会看到在tac 文件加载application 并正确格式化后记录的事件。

    您可以在logging howto 中阅读有关 Twisted 中日志记录如何工作的所有信息,以及如何在 application howto 中为twistd 配置它。

    另请注意,对 custom time formatting using datetime.strftime 的支持是 first introduced in Twisted 13.0.0。从您问题的输出来看,您似乎拥有 Twisted 12.0.0。这意味着格式化是使用time.strftime 完成的,它不支持微秒。

    在 Twisted 13.0.0 之前,要获取时间格式的微秒,您需要重写 FileLogObserverformatTime 方法并自己调用 datetime.strftime

    【讨论】:

    • 请问tac 文件是什么?我真的错过了正确的例子。
    • tac 文件是您编写的。这是一个 Python 语法文件,它定义了一个 application 全局名称(并且不调用 reactor.run)。
    • 好的,所以有一个误解,因为我的程序是我首先编写的,但它也包含我放置[...]我自己的许多其他类的位置,然后以 reactor.run 结束部分在同一个文件中。我刚刚删除了关于日志问题的不必要部分。
    • 对不起,我不明白你现在在问什么。
    • 请再问一个问题,当使用默认的log.startlogging(sys.stdout) 范例时,是否可以更改行为和格式?非常感谢
    【解决方案2】:

    如果这可以帮助这里的人(文件名为 my.tac)

    我还让 %z 正常工作(当使用我自己的时间格式而不是 +0000 时,我现在按预期得到 +0200)

    我用twistd -noy my.tac 调用它

    (灵感来自http://twistedmatrix.com/trac/browser/trunk/twisted/python/log.py#L407

    from twisted.application.service import Application
    from twisted.python.log import ILogObserver, FileLogObserver
    from twisted.python.logfile import DailyLogFile
    
    from datetime import datetime
    
    class MyFileLogObserver(FileLogObserver):
    
        def formatTime(self, when):
            """
            Format the given UTC value as a string representing that time in the
            local timezone.
    
            By default it's formatted as a ISO8601-like string (ISO8601 date and
            ISO8601 time separated by a space). It can be customized using the
            C{timeFormat} attribute, which will be used as input for the underlying
            L{datetime.datetime.strftime} call.
    
            BACKPORTED VERSION: and adding support for %z.
    
            @type when: C{int}
            @param when: POSIX (ie, UTC) timestamp for which to find the offset.
    
            @rtype: C{str}
            """
            tzOffset = -self.getTimezoneOffset(when)
            tzHour = abs(int(tzOffset / 60 / 60))
            tzMin = abs(int(tzOffset / 60 % 60))
            if tzOffset < 0:
                tzSign = '-'
            else:
                tzSign = '+'
            tz = "%s%02d%02d" % (tzSign, tzHour, tzMin)
            if self.timeFormat is not None:
                return datetime.fromtimestamp(when).strftime(self.timeFormat.replace("%z", tz))
    
            when = datetime.utcfromtimestamp(when + tzOffset)    
            return '%d-%02d-%02d %02d:%02d:%02d%s%02d%02d' % (
                    when.year, when.month, when.day,
                    when.hour, when.minute, when.second,
                    tzSign, tzHour, tzMin)    
    
    application = Application("myapp")
    logfile = DailyLogFile("my.log", "./")
    flo = MyFileLogObserver(logfile)
    flo.timeFormat = "%Y-%m-%d %H:%M:%S,%f%z"
    application.setComponent(ILogObserver, flo.emit)
    

    【讨论】:

    • 太棒了,如果我想将日志推送到 stdout 或 Python 中的其他名称,会有什么变化?
    猜你喜欢
    • 2011-04-11
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    相关资源
    最近更新 更多