Thought I’d play around today with adding a custom Event Log source to my windows service project – should be easy right?
Turns out Microsoft was wrong in documenting how to do this from a service because the MSDN code doesn’t work worth a shit. The *proper* way to do this is to implement this event installer code in your Service Installer and skip all the nonsense about “Event.CreateEventSource()”. While we are at it, I’ll go ahead and start my service automatically after install using a ServiceController() as seen below.
In your Service Installer, implement the following code:
using System.ServiceProcess;
using System.Diagnostics;
string eventSource = "MyService";
public MyServiceInstaller()
{
InitializeComponent();
EventLogInstaller installer = FindInstaller(this.Installers);
if (installer != null)
{
installer.Source = eventSource;
installer.Log = "My Custom Log Name";
}
}
private EventLogInstaller FindInstaller(InstallerCollection installers)
{
foreach (Installer installer in installers)
{
if (installer is EventLogInstaller)
{
return (EventLogInstaller)installer;
}
EventLogInstaller eventLogInstaller = FindInstaller(installer.Installers);
if (eventLogInstaller != null)
return eventLogInstaller;
}
return null;
}
protected override void OnCommitted(IDictionary savedState)
{
base.OnCommitted(savedState);
// Start the service after installation
using (ServiceController sc = new ServiceController(this.myServiceInstaller1.ServiceName))
{
sc.Start();
}
}
From your service, use the following code to log to the event log you just created in your installer:
string eventSource = "MyService";
public OptimizationService()
{
InitializeComponent();
EventLog.Source = eventSource;
EventLog.Log = "My Custom Log Name";
}
protected override void OnStart(string[] args)
{
EventLog.WriteEntry(eventSource, "My Service started.", EventLogEntryType.Information, 1234);
}
Here is the important part: Reboot your computer after installation of the service! If you don’t, you will see your custom event log created but the event entries won’t show up. Save yourself about 30 minutes of heartache (like I wish I did).
What you didn’ know that? It’s Windows! You need to reboot after everything!

