Change settings for eventlog in Service installer

I was developing a Windows service. Everything went smooth until I was asked to add logging for the service into a separate log file in the event viewer. I want to share my journey with you so it may help finding a solution for similar or the same issue.

After I had learned to install a service using a service installer, I ran into some troubles configuring the event viewer. My service had three logging options. First is to a text file on disk, second is to the Windows Event Viewer and I added an extra option to send a message to a messaging app. All service issues where logging fine. As a last option I was asked to log to a separate log in the event viewer like this:

First I tried adding all kind of options to my logging library to check, add and change the logging destination. That didn’t work and I found that the log needed to be set during initial installation of the service. Reason that previous attempts failed was that when changing these settings, the application needs admin privileges and changing logging options afterwards needed the machine to be rebooted etc.

I searched the internet for a solution and after a couple o hours I stumbled upon this article: https://stackoverflow.com/questions/115488/what-is-the-most-reliable-way-to-create-a-custom-event-log-and-event-source-duri

The post of Simon Mattes in this article helped me out. I altered the code a bit for my own use:

public ProjectInstaller()
{
InitializeComponent();
//Skip through all ServiceInstallers.
foreach (ServiceInstaller ThisInstaller in Installers.OfType())
{
//Find the first default EventLogInstaller.
EventLogInstaller ThisLogInstaller = ThisInstaller.Installers.OfType().FirstOrDefault();
if (ThisLogInstaller != null)
{
//Modify the used log from "Application" to the same name as the source name.
//This creates a source in the "Applications and Services log" which separates your service logs from the default application log.
ThisLogInstaller.Log = "TestApplication"; //ThisLogInstaller.Log = ThisLogInstaller.Source;
ThisLogInstaller.Source = "TestSource";
}
}
}

Check out this post on adding an installer to your application: http://kannekens.nl/registering-installing-a-windows-service-part-2/