Reporting an Error from win32service

983 Views Asked by At

Let's say I have a Service that I've written that's based on win32serviceutil.ServiceFramework like so:

class Launcher(win32serviceutil.ServiceFramework):
  _svc_name_ = "QueueFolders"
  _svc_display_name_ = "Queue Hot Folders"

  def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self, args)
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

  def SvcStop(self):
    sys.stopservice = True

  def SvcDoRun(self):
    # A call to something Main() like here.
    QueueFolders()

In this example calling QueueFolders instantiates an object that should be long-running if proper configuration has been done. If not, it raises an exception and I get this in my command prompt:

j:\EclipseWorkspace\Queue Folders\dist>net start queuefolders
The Queue Hot Folders service is starting.
The Queue Hot Folders service could not be started.

The service did not report an error.

More help is available by typing NET HELPMSG 3534.

I'm wondering, how would I report this error? I know I can try / catch my instantiation, but I've tried self.ReportServiceStatus(win32service.SERVICE_ERROR_CRITICAL) and still don't seem to be able to report anything meaningful back to the user (ideally, something in the form of "The service could not start, please check configuration."

1

There are 1 best solutions below

0
On BEST ANSWER

If SvcDoRun has a problem, you can call:

self.ReportServiceStatus(win32service.SERVICE_STOPPED, win32ExitCode=exit_code)

Where exit_code is a Windows system error code. Maybe you can find one of those that matches the error situation well enough. For example, if exit_code is winerror.ERROR_STACK_OVERFLOW, you'd see the following from net start QueueFolders:

The Queue Hot Folders service is starting.

The Queue Hot Folders service could not be started.

A system error has occurred.

System error 1001 has occurred.

Recursion too deep; the stack overflowed.

A similar message is displayed using the GUI service manager.

Furthermore, you can write to the Windows event log, which is a typical place to report service messages. To do that, use the servicemanager module.

For example:

def SvcDoRun(self):
    # oops something went wrong
    import servicemanager
    servicemanager.LogErrorMsg("Couldn't start - check your configuration")

Then, checking Event Viewer, in the Application section of the Windows Logs, you'd see your message.