mpaf
mpaf

Reputation: 6807

Python logging module doesn't work within installed windows service

Why is it that calls to logging framework within a python service do not produce output to the log (file, stdout,...)?

My python service has the general form:

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

The first call to logger.error produces output, but not the two inside the service class (even after installing the service and making sure it is running).

Upvotes: 3

Views: 3790

Answers (3)

SimaWB
SimaWB

Reputation: 9294

You have to write the full path of the log file.

e.g.

fh = logging.FileHandler('C:\\out.log')

Upvotes: 1

Kyle Johnson
Kyle Johnson

Reputation: 1675

I've found that only logging within the actual service loop works with the logging module and the log file ends up in something like C:\python27\Lib\site-packages\win32.

I abandoned logging with the logging module for Windows as it didn't seem very effective. Instead I started to use the Windows logging service, e.g. servicemanager.LogInfoMsg() and related functions. This logs events to the Windows Application log, which you can find in the Event Viewer (start->run->Event Viewer, Windows Logs folder, Application log).

Upvotes: 2

Scott 混合理论
Scott 混合理论

Reputation: 2332

actually outside logger initialized twice.

these 2 outside loggers are in different processes. one is the python process and another one is windows-service process.

for some reason, the 2nd one didn't configured success, and inside loggers in this process too. that's why u cant find the inside logs.

Upvotes: 0

Related Questions