Monday, August 24, 2009

Human Readable Entries For The Event Log

Looks like I've been a bit busy recently!
Anyway, just a little trick I used today to produce human readable messages for the event log, avoiding complex switches or if/else blocks.
First, I put all possible errors in the enum, including the "no error", like this:

public enum Errors
ProcessingCompletedSuccessfully = 0,
CouldNotEstablishConnectionToPrinter = 1,
GlobalSystemShutdownPreventedCompletingTheTaskInATimelyFashion = 999

The event log is created as usual

private System.Diagnostics.EventLog pollingEventLog;

if (!EventLog.SourceExists("MyHumbleSource"))
EventLog.CreateEventSource("MyHumbleSource", "MyHumbleService");
pollingEventLog.Source = "MyHumbleSource";
pollingEventLog.Log = "MyHumbleService";

The function should return the error code and the error code should be written to the event log

Errors error = PerformMyVeryComplexProcessing(XmlDocument data);

Finally, a small function that does the important stuff:

private void WriteErrorToLogFile(Errors error)
string inputstr = error.ToString();
Regex reg = new Regex(@"([a-z])[A-Z]");
MatchCollection col = reg.Matches(inputstr);
int iStart = 0;
string Final = string.Empty;
foreach (Match m in col)
int i = m.Index;
Final += inputstr.Substring(iStart, i - iStart + 1) + " ";
iStart = i + 1;
string Last = inputstr.Substring(iStart, inputstr.Length - iStart);
Final += Last;


I did not write the function myself - I got the solution from
Split words by capital letter using Regex

It takes the error, converts its name to string and splits the string by capital letters.
If the error returned was CouldNotEstablishConnectionToPrinter, then "Could Not Establish Connection To Printer" will be written to the event log.

by . Also posted on my website

No comments: