Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

Logging

Like performance counters, taking advantage of the event-logging mechanism offered by the operating system is a feature that almost all Windows services should utilize. To do so, the service class has two alternatives.

First, the service class itself will expose an EventLog property inherited from the ServiceBase class. This property exposes an EventLog object that can be used to write messages to the Application event log (as opposed to the System and Security logs), viewable from the Administrative Tools group or the Control Panel. Typically, the service class will log start, stop, pause, continue, exception, and other important events in the service's lifetime. In fact, by setting the AutoLog property of the service class, the service will log the start, stop, pause, and continue events automatically. It should be noted that the installer class can also include code in the AfterInstall and AfterUninstall methods to log messages when the service is installed or uninstalled using the installUtil.exe command-line utility. Secondly, the service can use the EventLog class directly by instantiating an object and settings its properties. In this case, it is effective to encapsulate the interaction with the log in a private method.

In either case, the EventLog object can be associated with a string referred to as a Source (typically set to the name of the service), under which the events from the service will be categorized in the event viewer. In that way, it's easy to see which events were generated from the service. Keep in mind that events can also be logged with various types that include information, warning, error, success audit, and failure audit. Event log sources can be created only by administrative accounts, so if the service runs under an account with lower privileges, the installer class can be used to create the event source.

Although most services log their events to the Application log, it is possible to add an instance of the EventLogInstaller class to the Installers collection of the installer class in order to create a custom log for messages that are only from the service. When using an event log, it's also important to remember that the log has settings that determine how many events are captured and for how long. If your service logs a large number of events, you'll need to be aware of these settings.

  • + Share This
  • 🔖 Save To Your Account