Logging Events in a Windows Service Program

ArmenB picture ArmenB · Nov 17, 2011 · Viewed 90k times · Source

I have created a Windows service program and I want my error to strictly be written to the Windows eventLog. So I followed these steps from code project article:

http://www.codeproject.com/KB/dotnet/simplewindowsservice.aspx

But I don't see any of the custom log messages I wrote in the event logs created in the event viewer window when I start or stop the service. Also how do I specify whether the message was due to an error or is just info?

Answer

alphadogg picture alphadogg · Nov 17, 2011

First, MSDN is your friend. Make sure you check out the link, as there are some potential gotchas worth knowing.

Essentially, you create an EventLog object:

this.ServiceName = "MyService";
this.EventLog = new System.Diagnostics.EventLog();
this.EventLog.Source = this.ServiceName;
this.EventLog.Log = "Application";

You also need to create a source, if the above source doesn't exist:

((ISupportInitialize)(this.EventLog)).BeginInit();
if (!EventLog.SourceExists(this.EventLog.Source))
{
    EventLog.CreateEventSource(this.EventLog.Source, this.EventLog.Log);
}
((ISupportInitialize)(this.EventLog)).EndInit();

and then simply use it:

this.EventLog.WriteEntry("My Eventlog message.", EventLogEntryType.Information);

it's actually pretty simple.