While developing any application logging the errors or exceptions is the key factor to improve the performance of the application. We can log the errors to the some text file or to the Application Log in Even Viewer. The advantage of logging to the Even Viewer is all errors related to system services are logged to Even Viewer, so if you log your application exceptions to Event Viewer also at one place you can monitor all at one place. Today we discuss how to log Exceptions to Applications to Event Viewer.
Open Microsoft Visual Studio => Create New Project => Create New Console Application
Use System.Diagnostics.EventLog namespace to log entry to Event Viewer. Create object for System.Diagnostics.EventLog and call WriteEntry() method of System.Diagnostics.EventLog to log entry as shown below.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
if (!System.Diagnostics.EventLog.SourceExists("MyApplicationLog"))
{
System.Diagnostics.EventLog.CreateEventSource("MyApplicationLog", "ErrorLog");
}
int i1 = 0;
int i2 = 200;
int i3 = i2 / i1;
}
catch (Exception ex)
{
System.Diagnostics.EventLog objLog = new System.Diagnostics.EventLog();
objLog.Source = "MyApplicationLog";
objLog.WriteEntry(ex.Message);
}
}
}
}
As shown above we are writing the Exceptions to Application Log in Event Viewer. Execute the application now. Then Open Event Viewer, the output is as shown below.