Free Information Technology Magazines and eBooks

Sunday, May 03, 2009

C#: How to Write to Windows Event Log

Application log is a must for good programmers to troubleshoot applications problems. Most of these logs are written on text file or database. But these types of logs are only good if the programmer himself is the one whos supporting his own software. If your creating a windows service that will be administered by system adminitrators it would be a best practice to write your logs on Windows Event Log. This way your system administrator will be notifed in case some failures or important events occur.

Here's how to do it in C#:
First, add System.Diagnostics namespace on your Using Directives:

using System.Diagnostics;


Now Let's code the event log function:
public void WriteEventToWindowsLog(string strMyApp, string strEvent)
{
if (!System.Diagnostics.EventLog.SourceExists(strMyApp))
System.Diagnostics.EventLog.CreateEventSource(strMyApp, "Application");

EventLog MyEventLog = new EventLog();
MyEventLog.Source = strMyApp;
MyEventLog.WriteEntry (strEvent, EventLogEntryType.Warning);
}


Just include the WriteEventToWindowsLog function above to your application and you already got your windows event logger.

For more C# Tips and Tricks, subscribe now

4 comments:

Anonymous said...

Just what I was looking for. Thanks!

Anonymous said...

Me too! Nice and concise. Thanks for posting it. Better than a lot of snippets because you point out the refernece assembly. Kudos!

Eng.Waleed said...

Windows Event Helper C# "Integration with EventLog"::
http://ledomoon.blogspot.com/2008/08/windows-event-helper-c-with-eventlog.html

Anonymous said...

Bad news: It does not work with Windows Vista and Windows 7 bewcause EventLog.SourceExist() also scans the Security-Log and for that you need to elevate your privilege to Admin-Privileg.
For more info see: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx