Wednesday, April 30, 2008

How to write to the Windows event log using .NET

In the .NET framework you have the System.Diagnostics.EventLog class which provides static methods for working with the Windows event log.

In order to write a new entry to the event log, you can use the WriteEntry method as follows:

using System.Diagnostics;

...

EventLog.WriteEntry("My Application", "My message", EventLogEntryType.Error);

The EventLogEntryType enumeration has the following members: Error, FailureAudit, Information, SuccessAudit, Warning.

If the event source "My Application" doesn't exist, then the WriteEntry method will try to create it. However, if the current process runs under a non-admin account, then this may fail due to lack of permissions. In that case, you can create a console application, which creates the event source by using the CreateEventSource method:

using System;
using System.Diagnostics;

namespace CreateEventSource
{
 class Program
 {
  static void Main(string[] args)
  {
   if (args.Length == 0)
   {
    Console.WriteLine("The event source name is required as an argument.");
    return;
   }
   
   string source = args[0];
   
   try
   {
    if (!EventLog.SourceExists(source))
    {
     EventLog.CreateEventSource(source, "Application");
     Console.WriteLine("The event source {0} was successfully created.", source);
    }
    else
    {
     Console.WriteLine("The event source {0} already exists.", source);
    }
   }
   catch(Exception ex)
   {
    Console.WriteLine("The event source {0} was not created due to: \n{1}", source, ex.ToString());
   }
  }
 }
}

During installation of your application, you run this console application to register the necessary event source(s). Make sure you are logged in as the admin user when you run it.