Modifying the Service to Add Messages
Finally we are ready to change our service to use the Event Log. We will change the service to write messages as it starts and stops, and also after each user has connected.
We add the code for the service starting message at the start of the
service’s SvcDoRun() method. A good place to
add the service stopping message is just as this function returns.
The top of this function now looks like:
def SvcDoRun(self):
# Log a "started" message to the event log.
import servicemanager
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_, ''))And the last lines are:
# Now log a "service stopped" message
servicemanager.LogMsg(
servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))Note that you import the servicemanager object at
the start of the function. This is because, as described previously,
it’s provided by the host .exe so it
can’t be imported at the top level of the program. To write a
message as the user disconnects, insert this code:
# Log a message to the event log indicating what we did. message = "Processed %d bytes for client connection" % len(data) servicemanager.LogInfoMsg(message)
Let’s see our code in action. First, let’s run this service in debug mode. From a command prompt, type:
C:\Scripts> PipeService2.py debug Debugging service PythonPipeService Info 0x40001002 - The PythonPipeService service has started.
Now make a client connection ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access