我正在尝试将Twisted和Python一起使用。我需要将异常和错误导出到一个文件而不是控制台,以防在运行时出现任何意外,并且我碰巧错过了它,但是重定向stderr似乎不起作用。错误仍然显示在控制台中,并且不会写入文件(尽管文件已创建(。
这里有一个最小的例子:
from twisted.internet import reactor
import sys
sys.stderr = open('error.log', 'a')
def error_test():
int("Hello")
reactor.callLater(1, error_test)
reactor.run()
我做错了什么?
您可以使用twist
(或twistd
(来配置日志记录。例如:
$ twist --log-file /tmp/some-file --log-format=text --log-level info web
^C
$ cat /tmp/some-file
2020-10-18T10:35:41-0400 [-] Site starting on 8080
2020-10-18T10:35:41-0400 [twisted.web.server.Site#info] Starting factory <twisted.web.server.Site instance at 0x7fe59bbf4d70>
2020-10-18T10:35:41-0400 [twisted.application.runner._runner.Runner#info] Starting reactor...
2020-10-18T10:35:44-0400 [-] Received SIGINT, shutting down.
2020-10-18T10:35:44-0400 [-] (TCP Port 8080 Closed)
2020-10-18T10:35:44-0400 [twisted.web.server.Site#info] Stopping factory <twisted.web.server.Site instance at 0x7fe59bbf4d70>
2020-10-18T10:35:44-0400 [-] Main loop terminated.
$
这只需要将你的应用程序构建为一个twist可以找到并启动的插件。
有关此方法的更多信息,请访问https://twistedmatrix.com/documents/current/core/howto/tap.html(为twistd
编写插件与为twist
编写插件相同(。
您也可以通过编程方式配置日志系统。例如:
import sys
from twisted.logger import globalLogBeginner
from twisted.logger import textFileLogObserver
globalLogBeginner.beginLoggingTo([textFileLogObserver(sys.stderr)])
from twisted.internet import reactor
def error_test():
int("Hello")
reactor.callLater(1, error_test)
reactor.run()
它将日志发送到stderr,如下所示:
$ python /tmp/demo.py 2>/tmp/demo-err
^C
$ cat /tmp/demo-err
2020-10-18T10:43:15-0400 [-] Unhandled Error
Traceback (most recent call last):
File "/tmp/demo.py", line 15, in <module>
reactor.run()
File "twisted/internet/base.py", line 1283, in run
self.mainLoop()
File "twisted/internet/base.py", line 1292, in mainLoop
self.runUntilCurrent()
--- <exception caught here> ---
File "twisted/internet/base.py", line 913, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/tmp/demo.py", line 11, in error_test
int("Hello")
exceptions.ValueError: invalid literal for int() with base 10: 'Hello'
2020-10-18T10:43:17-0400 [-] Received SIGINT, shutting down.
2020-10-18T10:43:17-0400 [-] Main loop terminated.
您可以在上了解有关twisted.log的更多信息https://twistedmatrix.com/documents/current/core/howto/logger.html