使用 twisted.python.log 的代码出现扭曲试验错误

Twisted trial error on code that uses twisted.python.log

我似乎无法在同一段代码上登录到标准输出和 运行 试用版。

temp.py

from sys import stdout
from twisted.python.log import startLogging
startLogging(stdout)

class Foo(object):
    pass

temp_test.py

from twisted.trial import unittest
from temp import Foo

class FooTestCase(unittest.TestCase):
    pass

输出

2015-07-27 17:45:06-0400 [-] Log opened.
2015-07-27 17:45:06-0400 [-] Unable to format event {'log_namespace': 'twisted.logger._global', 'log_level': <LogLevel=warn>, 'fileNow': '/Users/james/Dropbox/code/demo/server/venv/lib/python2.7/site-packages/twisted/python/log.py', 'format': '%(log_legacy)s', 'lineNow': 210, 'fileThen': '/Users/james/Dropbox/code/demo/server/venv/lib/python2.7/site-packages/twisted/python/log.py', 'log_source': None, 'system': '-', 'lineThen': 210, 'log_logger': <Logger 'twisted.logger._global'>, 'time': 1438033506.184351, 'log_format': 'Warning: primary log target selected twice at <{fileNow}:{lineNow}> - previously selected at <{fileThen:logThen}>.  Remove one of the calls to beginLoggingTo.', 'message': (), 'log_time': 1438033506.184351}: Invalid conversion specification
2015-07-27 17:45:06-0400 [-] Log opened.

为什么这段代码失败了?它似乎正在尝试开始记录两次?


我确实注意到 twisted.python.log 已被 twisted.logger 取代;它应该只是一个包装器。 Logger class 似乎与 startLogging(stdout) 没有直接的类比。

这里的部分问题是 a bug that has already been fixed in Twisted,这里是警告字符串的格式。

但是,真正的问题是您开始记录两次,一次是通过 运行ning trial,它设置自己的日志观察器来捕获记录的异常,一次是通过调用 startLogging 在模块范围内。如果你使用 the new API for doing this,你会得到类似的错误,所以切换到 twisted.logger,虽然在长 运行 中是个好主意,但实际上并没有关系。

正确的解决办法通常是不要自己开始记录;让 twistdtrial 为您完成。如果你确实需要自己启动它,它应该在 main 函数的上下文中,当启动你的程序 "for real" 时,它只是 运行,在 trial 之外,因为例如。