gpt4 book ai didi

python - 扭曲并将异常写入stderr

转载 作者:行者123 更新时间:2023-12-03 08:38:27 25 4
gpt4 key购买 nike

我正在尝试同时使用Twisted和Python。我需要将异常和错误导出到文件而不是控制台,以防在运行时突然 pop 任何意外消息并且我碰巧错过了它,但是重定向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.
$
这仅需要将您的应用程序构建为可以扭曲并启动的插件。
有关此方法的更多信息,请访问 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.
您可以在 https://twistedmatrix.com/documents/current/core/howto/logger.html上了解有关twisted.logger的更多信息。

关于python - 扭曲并将异常写入stderr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64404157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com