微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

扭曲并将异常写入stderr

如何解决扭曲并将异常写入stderr

我正在尝试同时使用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.
$

这仅需要将您的应用程序构造为一个可以扭曲并启动的插件。

有关此方法的更多信息,请访问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的信息。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。