Custom Event Logger for .Net 3.5 and .Net 4.0

>> Sunday, July 31, 2011

I needed to write a .Net 3.5 Event logger for a custom lib I am coding for a client. After scouring the internet, there were a lot of antiquated code samples. I even found a lot of modern samples on MSDN, but was surprised to see very poor code (having a .close() not within a using() or finally())

I decided to write a custom Event logger class with the following simple functionality, since the primary use was to report events or errors.

  • Have a write() event that would log a custom error to the event log (found in the System logs)
  • Would write to a text file in the event the Event did not get logged. I found this step necessary since the calling program may not have Event log access due to security.

Here is the Class:

class CustomEventLog
    {
        const string sourceName = "Your custom event name here";
        const string logType = "System";
        const string customTextLog = "c:\\CustomEventLog.log";

        public static void Write(string message, EventLogEntryType type)
        {
            try
            {
                //See if the source exists. 
                if (!(EventLog.SourceExists(sourceName, System.Environment.MachineName)))
                {
                    System.Diagnostics.EventLog.CreateEventSource(new EventSourceCreationData(sourceName, logType));
                }

                using (EventLog ev = new EventLog(logType, System.Environment.MachineName, sourceName))
                {
                    ev.WriteEntry(message, type, 10001);
                    Console.WriteLine(message);
                    ev.Close();
                }
            }
            catch (Exception ex)
            {
                // If all else fails write to disk
                using (StreamWriter sw = new StreamWriter(customTextLog, true))
                {
                    sw.WriteLine(ex.ToString());
                    if (message != null)
                    {
                        sw.WriteLine(message);
                    }
                    sw.Close();
                }
            }
        }
    }

Here is also sample usage:

CustomEventLog.Write("This is an informational comment.", EventLogEntryType.Information);

2 comments:

ADmin March 9, 2013 at 6:38 AM  

Knowing your end before you start is one of the most ideal click here courses to guarantee that you will arrive there.

Asava Samuel April 10, 2013 at 4:36 PM  

This is a great logging library:
http://www.kellermansoftware.com/p-14-net-logging-library.aspx

  © Blogger templates Sunset by Ourblogtemplates.com 2008

Back to TOP