Monthly Archives: April 2009

Coding EventLog Excellence

Summary

It’s a best practice to have all custom code write to the event log.   Every code execution should produce one and only one log entry.   Exceptions (code speak for err) should be written here.    For troubleshooting and support you can’t ask for a better tool.    The framework exists, EventCombMT helps aggregate, and it allows you to run dozens … or hundreds … of apps while keeping a sharp eye on quality control.

Namespaces

System.Diagnostics.EventLog

Example

clip_image002

 

static void Main(string[] args)
{
    try {
        //Main code procedure
        Console.WriteLine("Hello World!");
        writeEventlog(1, null);         //Write to Eventlog – GOOD 
    }
    catch (System.Exception e)
    {
        writeEventlog(2, e);            //Write to Eventlog – BAD
    }
}
static void writeEventlog(int success, System.Exception e)
{
    //Current EXE name
    String exe = System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(‘,’)[0];
    String header = "";
    String exception = "";
    EventLogEntryType type = EventLogEntryType.Information;
   
    //Determine type
    switch (success)
    {
        case 1:
            header = "nOperation successfully completed";
            break;
        case 2:
            header = "nOperation FAILED";
            if (e != null) strException = e.Message + e.InnerException + e.StackTrace;
            type = EventLogEntryType.Error;
            break;
        case 3:
            header = "nOperation WARNED";
            if (e != null) exception = e.Message + e.InnerException + e.StackTrace;
            type = EventLogEntryType.Warning;
            break;
    }
 
    //Write to log
    EventLog myLog = new EventLog("Application", ".", exe);
    myLog.WriteEntry(exe + "n" + exception, type);
}
Return to Top ▲Return to Top ▲