Python 日志记录模块在已安装的 Windows 服务中不起作用

标签 python logging windows-services pywin32

为什么调用 python 服务中的日志框架不会生成日志输出(文件、stdout,...)?

我的 python 服务具有一般形式:

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('out.log')
logger.addHandler(fh)

logger.error("OUTSIDE")

class Service (win32serviceutil.ServiceFramework):
    _svc_name_ = "example"
    _svc_display_name_ = "example"
    _svc_description_ = "example"

    def __init__(self,args):
        logger.error("NOT LOGGED")
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
              servicemanager.PYS_SERVICE_STARTED,
              (self._svc_name_,''))

    def SvcStop(self):

        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.stop = True

    def SvcDoRun(self):

        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        self.main()

    def main(self):
        # Service Logic
        logger.error("NOT LOGGED EITHER")
        pass

第一次调用 logger.error 会产生输出,但不会产生服务类内的两个输出(即使在安装服务并确保其正在运行之后)。

最佳答案

我发现只有在实际服务循环中进行日志记录才可以使用日志记录模块,并且日志文件最终会出现在类似 C:\python27\Lib\site-packages\win32 中。

我放弃了使用 Windows 的日志记录模块进行日志记录,因为它看起来不太有效。相反,我开始使用 Windows 日志服务,例如servicemanager.LogInfoMsg() 及相关函数。这会将事件记录到 Windows 应用程序日志中,您可以在事件查看器中找到该日志(开始->运行->事件查看器、Windows 日志文件夹、应用程序日志)。

关于Python 日志记录模块在已安装的 Windows 服务中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14813614/

相关文章:

c# - 在滚动文件的顶部仅包含一次标题

java - 在 Java 中禁用 Log4J 输出

python - 对数据框列中的值进行自定义过滤器 (Python)

python - 为 python/pandas 中的每一行分配组平均值

python - python 中 BPY 模块的导入错误

logging - Fluentd + golang 日志记录应用程序出错

c# - Windows 服务 SQL Server 错误 - "Login failed for user"

windows-services - 服务安装失败,因为事件源已存在

f# - 在 F# : "No public installers with the RunInstallerAttribute.Yes attribute ..." 中安装 Windows 服务

javascript - Bokeh div 小部件,通过按按钮更改文本