How To Write to the Event Log in C#

I've been doing a lot of C# developing for Microsoft Exchange lately and I would like to share with you a few lines of C# that I've found to be very useful in event handling.

I prefer using the windows event logs and not text files for logging since they will not grow out of control and are very easy to search and handle.

The function below will create an event in the specified log, under the specified source with the provided information:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
        private static void WriteEvent(String LogName, String EventSource, String EventBody, int EventId, EventLogEntryType EventType)
        {
            try
            {
                using (EventLog eventLog = new EventLog(LogName))
                {
                    if (!EventLog.SourceExists(EventSource))
                        EventLog.CreateEventSource(EventSource, LogName);

                    eventLog.Source = EventSource;
                    eventLog.WriteEntry(EventBody, EventType, EventId);
                }
            }
            catch(Exception e)
            {
                throw e;
            }
        }

Let's break it down!

First, on line 5, we are using the LogName parameter to create an instance of the EventLog class. Then, on lines 7 and 8, we check if the source exists and if not we create it. In case we create the source, the process has to be running with elevated rights.

After the source check, we set the source on the eventLog object and we call the WriteEntry method to create the event. This method accepts the following parameters:
    1. EventBody: The body of the message.
    2. EventType: The type of the event (informational, warning, etc)
    3. EventId: The id of the event

I have not added exception handling in this example since you should treat the exceptions your selves. Moreover, you have to include the System.Diagnostics runspace.

Furthermore, you can also create the event source using Powershell beforehand and you will not have to run your program with elevated rights.

I hope you find this helpful!

Popular posts from this blog

Domain Controller Machine Password Reset

Managing Active Directory User Certificates using PowerShell

Configuring a Certificate on Exchange Receive Connector