Saturday, August 11, 2012

C# Write to Windows Event Log


As you probably know Windows has its own Event Logging System. You can see the logs in it if you'll run Event Viewer from Administrative Tools. Today I'll show how to write messages into Windows Event Log from your application using C#.
Microsoft Windows Event Viewer

In order to write to Event Log you have to include System and System.Diagnostics namespaces in your code.
   using System;
   using System.Diagnostics;
The log message that will be inserted to event log consists of three things - the message itself, the name of the log to which you want to write your message (if such log does not exist it will be created) and a string that represents the source of your event. If you need to write messages to more than one log you must define multiple sources.
   string _source = "My Application";
   string _log = "Application";
   string _event = "My Application Event";
You have to check if the source that you specified really exists, if it doesn't then create it. If the log name that you specified does not exist, then it will be created automatically when you write your first message.
   if (!EventLog.SourceExists(_source))
       EventLog.CreateEventSource(_source, _log);
In order to write a message use EventLog.WriteEntry static method. WriteEntry has several overloaded versions, here is the simplest one:
   EventLog.WriteEntry(_source, _event);
Run the following code, then go to the Event Viewer and check your logs.
using System;
using System.Diagnostics;

namespace WriteToAnEventLog_csharp
{    
    class MyEvent
    {
        static void Main(string[] args)
        {
            string _source = "My Application";
            string _log = "Application";
            string _event = "My Application Event";

            if (!EventLog.SourceExists(_source))
                EventLog.CreateEventSource(_source, _log);

            EventLog.WriteEntry(_source, _event);
            EventLog.WriteEntry(_source, _event, EventLogEntryType.Warning, 234);
        }
    }
}
Good luck!

1 comment: