Python Windows 服务 - 日志记录不工作

Python Windows Service - Logging not working

使用 Python 3.7,Windows 10 Pro,Pywin32

我有一个测试脚本,它启动服务并在发出不同命令时将一些基本行推送到日志文件中。代码如下:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging


class AppServerSvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"
    _svc_description_ = "New Test Service"

    logging.basicConfig(filename='search_server.log', level=logging.INFO)
    logging.info('Class opened')

    def __init__(self, args):
        logging.basicConfig(filename='search_server.log', level=logging.INFO)
        logging.info('Init')
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)


    def SvcStop(self):
        logging.basicConfig(filename='search_server.log', level=logging.INFO)
        logging.info('Stop')
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)


    def SvcDoRun(self):
        logging.basicConfig(filename='search_server.log', level=logging.INFO)
        logging.info('Run')
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()


    def main(self):
        print("running")
        logging.basicConfig(filename='search_server.log', level=logging.INFO)
        logging.info('Main')


if __name__ == '__main__':
    logging.basicConfig(filename='search_server.log', level=logging.INFO)
    logging.info('Calling Handle Command Line')
    win32serviceutil.HandleCommandLine(AppServerSvc)

我已经完成了基本的故障排除,服务正在安装、启动、重新启动和删除,没有任何错误。但是,我希望日志文件能够接收到基本输出以显示函数被命中,但事实并非如此。

我在管理员命令提示符下进行的调用:

C:\PythonScripts\SearchServer>python servicetest.py install
Installing service TestService
Service installed

C:\PythonScripts\SearchServer>python servicetest.py start
Starting service TestService

C:\PythonScripts\SearchServer>python servicetest.py restart
Restarting service TestService

C:\PythonScripts\SearchServer>python servicetest.py remove
Removing service TestService
Service removed

C:\PythonScripts\SearchServer>

日志文件的内容:

INFO:root:Class opened
INFO:root:Calling Handle Command Line
INFO:root:Class opened
INFO:root:Calling Handle Command Line
INFO:root:Class opened
INFO:root:Calling Handle Command Line
INFO:root:Class opened
INFO:root:Calling Handle Command Line

如您所见,每次发出命令时都会调用服务,但我希望内部函数也被调用。作为这两种服务的新手和 Python 我想知道我是否错过了什么?我假设函数名称是预定义的,不需要我设置委托来访问它们。这不是我在遇到的任何问题中看到的。

我当然假设这些函数应该被命中并且它们正在被命中并且能够创建日志?

感谢收到的任何帮助。

代码有一些问题:

  1. logging.basicConfig()只能调用一次,再调用将不会有任何效果。
  2. Class 定义将首先在您的代码中调用,甚至在块 if __name__ == '__main__': 之前,因为代码的自然流动。因此,无论您在 class 定义中的 logging.basicConfig() 中设置什么,都将成为整个脚本的最终结果。这不是这个设置的理想位置,所以应该移到别处(在顶部,最好在 class 之外)。
  3. logging.basicConfig传入的
  4. filename参数应该是文件的绝对路径,因为一旦服务启动运行,它的当前路径就不会和脚本一样了,所以logging不会能够找出日志文件。 (该服务的当前工作目录将变成类似 C:\Python37\lib\site-packages\win32 的目录)。
  5. (可选):尽量不要使用根日志记录配置,最好有一个记录器实例供您自己使用。

完成所有这些更改后,脚本将如下所示:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging.handlers

log_file_path = ""  # mention full path here
mylogger = logging.getLogger("TestLogger")
mylogger.setLevel(logging.INFO)
handler = logging.handlers.RotatingFileHandler(log_file_path)
mylogger.addHandler(handler)

class AppServerSvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _svc_display_name_ = "Test Service"
    _svc_description_ = "New Test Service"

    mylogger.info('Class opened')

    def __init__(self, args):
        mylogger.info('Init')
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)


    def SvcStop(self):
        mylogger.info('Stop')
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)


    def SvcDoRun(self):
        mylogger.info('Run')
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()


    def main(self):
        print("running")
        mylogger.info('Main')

if __name__ == '__main__':
    mylogger.info('Calling Handle Command Line')
    win32serviceutil.HandleCommandLine(AppServerSvc)

输出:

Class opened
Init
Run
Main
Class opened
Calling Handle Command Line

我在 python 日志记录方面遇到了无法解释的问题,我通过在程序开头设置日志记录解决了这些问题:

import logging
logging.basicConfig(filename='convert_st.log', level=logging.INFO)
logging.info('Started')

import all_other_packages
import...
...

def main:
   # main comes here
   ...

if __name__ == '__main__':
    main()