Sunday, July 31, 2011

Custom Event Logger for .Net 3.5 and .Net 4.0

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);

1 comment:

ADmin said...

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