Wednesday, April 14, 2010

c# System Event logging

Here is a simple c# method to write errors to the event log which captures the calling class and method and an error and writes them to the event log for centralized error reporting.

I don't know about you but I hate to have to track down where someone writes error messages too, so I of course encourage my employees to write any issues to an event log.

This method returns false if it fails to write to the event log.

public static bool Log_writeError(string sMessage)
{
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();

EventLog myLog = new EventLog();
myLog.Source = methodBase.ReflectedType.FullName + "." + methodBase.Name;
myLog.Log = "Application";

try
{
myLog.WriteEntry(sMessage, EventLogEntryType.Error);
}
catch
{
return false;
}

return true;
}

And now we make the call:
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.logentry();
Console.ReadKey();
}

public void logentry()
{
if (!logger.Log_writeError("Test Message"))
Console.WriteLine("Failed to write to event log");
}
}

and we can now see an entry for our Source in the Application log:



No comments:

Post a Comment