How to Create Custom Event Log for Windows Service

When you created a Windows Service, you usually add a Service Installer to allow this service to be installed using InstallUtil or installing it programmatically like this post shows you.

The service installer will create the Event Log for the service, and by default it is "Application", and the source is the name of your service.

The Event Source is most likely to be fine, but the event log may need to be set to something else. Unfortunately, the option is not visible from the installer.

The Installer object for your windows service, actually hosted several other Installer objects, one of the child Installer is responsible to create the Event Log. You need to find this object and then changed the Log property and it will create the appropriate event log. It is easy to find this object as this object is an instance of EventLogInstaller.

The code:

public partial class MyServiceInstaller : Installer
{
    private const stringLogName = "My Service Log";

    public MyServiceInstaller()
    {
        InitializeComponent();

        EventLogInstaller EventLogInstall = null;

        foreach (Installer I in this.serviceInstaller.Installers)
        {
            EventLogInstall = I as EventLogInstaller;

            if(EventLogInstall != null)
            {
                EventLogInstall.Log = LogName;
                EventLogInstall.UninstallAction = UninstallAction.NoAction;
                break;
            }
        }
    }
}

That code above shows how to create a custom Event Log for your service, the code also shows that the custom event log will never be uninstalled, depending on the requirements it can be easily changed.

If the event source needs to be changed as well, simply change the Source property and you are set.

One thing to pay attention, if you create a custom event log, you install the service programmatically, and your service is running with a restricted account, then you have to modify the code to install the service by adding a code to write one entry to the event log that you just created.

After the service installer is executed, the log is 'registered', but not created yet. To create it, one event must be written. If the service runs using a restricted user account, that account may not have enough security permission to write the first log, as the log need to be created.

When installing the service, the user must run the installer as Administrator, so the installer has all security privilege that it needs. So remember to write one event entry after programmatically installing the service.