Python Windows服务-日志记录不起作用

时间:2019-08-19 15:06:02

标签: python windows logging service pywin32

使用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)

与此相关的我已经经历了基本的故障排除,该服务正在安装,启动,重新启动并被删除,没有任何错误。但是,我希望日志文件接收基本输出,以表明功能已被命中,但事实并非如此。

我正在admin命令提示符下拨打的电话:

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 个答案:

答案 0 :(得分:3)

代码有一些问题:

  1. logging.basicConfig()应该仅被调用一次,如果再次调用将没有任何作用。
  2. 由于自然的代码流,类定义将在代码中首先被调用,甚至在块if __name__ == '__main__':之前。因此,您在类定义中的logging.basicConfig()中设置的所有内容对于整个脚本而言都是最终的。对于此设置而言,这不是理想的地方,因此应将其移至其他位置(顶部,最好是在课堂之外)。
  3. 在logging.basicConfig中传递的
  4. filename参数应为绝对文件路径,因为一旦服务开始运行,其当前路径将与脚本相同,因此日志记录将无法找到日志文件。 (该服务的当前工作目录将类似于C:\ Python37 \ lib \ site-packages \ win32)。
  5. (可选):尝试一点都不使用root日志配置,最好有一个logger实例供您自己使用。

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

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