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:
Knowing your end before you start is one of the most ideal click here courses to guarantee that you will arrive there.
Post a Comment