【问题标题】:How to set twistd.py ILogObserver when using IPlugin?使用IPlugin时如何设置twistd.py ILogObserver?
【发布时间】:2023-12-08 21:08:01
【问题描述】:

我想将 twistd.py 的日志重定向到 python 的日志。正常启动.tac 文件时,我可以轻松做到这一点:

from twisted.python.log import PythonLoggingObserver, ILogObserver
from twisted.application import service

application = service.Application("FooApp")
application.setComponent(ILogObserver, PythonLoggingObserver().emit)

但是,在编写IPlugin 时,我似乎没有Application。相反,我只有一个实现IServiceMakerIPlugin 的类,其中makeService 返回service.Service。如何设置这个日志观察器?

请注意,我不只是想添加一个 python 日志观察器,我想重定向 twistd 的日志记录,以便它只通过 python 的内置日志记录系统。

【问题讨论】:

    标签: python logging twisted twistd


    【解决方案1】:

    看twistd的--logger参数:

    # mylogger.py
    from twisted.python import log
    
    def logger():
        return log.PythonLoggingObserver().emit
    

    然后调用twistd:twistd --logger=mylogger.logger

    【讨论】:

    • 似乎可以工作 - 我之前忘记设置 python 日志记录,但我之前说没有。谢谢!