如何更改 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)