Thursday, August 13, 2009

How to log the Error/ Exceptions details into the event viewer using c#?

Any kind of exception or error can be logged into the event viewer using few lines of code by writing into Global.asax.cs file of your application.
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
/// Get reference to the source of the exception chain and log the exception into Event Log
void Application_Error(object sender, EventArgs e)
{
//Get reference to the source of the exception chain
Exception ex = Server.GetLastError().GetBaseException();

//Log the details of the exception and page state to the
//Windows 2000 Event Log
EventLog.WriteEntry("My Application",
"MESSAGE: " + ex.Message +
"\nSOURCE: " + ex.Source +
"\nFORM: " + Request.Form.ToString() +
"\nQUERYSTRING: " + Request.QueryString.ToString() +
"\nTARGETSITE: " + ex.TargetSite +
"\nSTACKTRACE: " + ex.StackTrace,
EventLogEntryType.Error);
}

1 comment:

  1. This is simple way of tracking the exceptions on the servers but these exceptions can also be tracked by using custom C# classes.

    ReplyDelete