Event Viewer Logging via .NET EventLog
Today, I will provide you an easy way of putting a log information for your application under Event Viewer. Of course, professionally I would advise you to make your own or use better log frameworks like log4net or ELMAH for your .NET applications. But what I show you here is too handy in start-up and development environments. So if you are trying something or proving the concept first at your application, you can use the below very simple code block to take your applications log.
Logged records are hold by windows default Event Viewer. If you want to have an appropriate source location at Event Viewer, than you need to open Event Viewer under Administative Tools and manually create it.
Below class implementation can store your exceptions and informations using EventLog object of .NET Framework
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
public static class Log { public static string LogName { get { string logName = ConfigurationManager.AppSettings["LogName"]; return logName == null ? "My APP" : logName; } } public static void WriteTraceLog(string message) { EventLog appLog = CreateEventLog(LogName); appLog.WriteEntry(message, EventLogEntryType.Information); } public static void WriteExceptionLog(Exception ex) { EventLog appLog = CreateEventLog(LogName); appLog.WriteEntry(ex.Message + "\r\n=== Stack Trace ===\r\n" + ex.StackTrace, EventLogEntryType.Error); if (ex.InnerException != null) { WriteExceptionLog(ex.InnerException); } } private static EventLog CreateEventLog(string logName) { EventLog appLog = new EventLog(logName); appLog.Source = logName; if (!EventLog.SourceExists(appLog.Source)) EventLog.CreateEventSource(appLog.Source, logName); return appLog; } } |




