如何在多个守护进程/定时任务脚本中使用原生Python日志或Twisted日志?
我在一个程序中使用日志记录,涉及到不同的脚本,比如定时任务、Twisted守护进程(像是处理一些数据的Http服务器)等等。
如果我在基础类中使用默认的Python日志记录,比如
import logging
import logging.handlers
....
self.__fname = open(logname, 'a')
logging.basicConfig(format=FORMAT, filename=logname, handler=logging.handlers.RotatingFileHandler)
self._log = logging.getLogger(self.__pname)
self._log.setLevel(loglevel)
logging.warn('%s %s \033[0m' % (self.__colors[colortype], msg))
这样的话,所有脚本的输出都会正常记录到一个文件里,但有些重要的Twisted默认日志信息就缺失了,比如关于HTTP请求和头部的信息等等。
如果我使用Twisted的日志记录,比如
from twisted.python.logfile import DailyLogFile
from twisted.python import log
from twisted.application.service import Application
....
application = Application("foo")
log.startLogging(DailyLogFile.fromFullPath(logname))
print '%s %s \033[0m' % (self.__colors[colortype], msg)
这样就可以记录到额外的数据,但不同脚本的日志记录就出现了一些问题——看起来定时任务的日志输出有点麻烦。好像这些定时任务在输出时切换了上下文,导致部分日志输出丢失,无法恢复。
当然,定时任务是独立于Twisted反应器运行的,但我还是在使用Twisted的日志记录。
我该如何处理日志记录,以便同时记录Twisted和定时任务部分的所有数据呢?
谢谢任何帮助!
1 个回答
2
我觉得关键在于,你应该使用 PythonLOggingObserver,而不是 DailyLogFile,这样可以把日志重定向到标准库的日志中。
from twisted.python import log
observer = log.PythonLoggingObserver()
observer.start()
log.msg('%s %s \033[0m' % (self.__colors[colortype], msg))
另外,你可能还想看看文档中的示例:http://twistedmatrix.com/documents/current/core/howto/logging.html#auto3