Error Logging using ASP.NET 2.0
Errors
and failures may occur during development and operation of a website.
ASP.NET 2.0 provides tracing, instrumentation and error handling
mechanisms to detect and fix issues in an application.
In
this article, we will adopt a simple mechanism to log errors and
exceptions in our website. We will be using a mechanism where the user
will be redirected to a separate page whenever an error is encountered
in the application. Simultaneously, the error will get logged in a text
file on the server. The error file will be created on a daily basis,
whenever the error is encountered. Having said that, let us now see
some code.
Step 1:
Start by creating an Error folder where all errors will be logged.
Right click the website > New Folder. Rename the folder to “Error”.
Also add a web.config file, if one does not already exist in your site.
Right click the website > Add New Item > Web.config.
Step 2:
Now we will create the error handler code. To do so, right click your
website > Add New Item > select Class. Rename the class to
‘ErrHandler.cs’ and click on ‘Add’. When you do so, you will be
prompted with a message to place the class in ‘App_Code’ folder. Accept
the message to place the class in the 'App_Code' folder.
Step 3:
Now let us add functionality to the ErrHandler class. This class will
accept the error message and write the message in a text file. One text
file will be created for each day. If the text file already exists, the
message will be appended to the text file. If not, a new text file will
be created based on today’s date and error message will be written in
it.
The code will look similar to the following:
C#
/// Handles error by accepting the error message
/// Displays the page on which the error occured
public static void WriteError(string errorMessage)
{
try
{
string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine(""r"nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + errorMessage;
w.WriteLine(err);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}
VB.NET
''' Handles error by accepting the error message
''' Displays the page on which the error occured
Public Shared Sub WriteError(ByVal errorMessage As String)
Try
Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log Entry : ")
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))
Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage
w.WriteLine(err)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
Catch ex As Exception
WriteError(ex.Message)
End Try
End Sub
That
was our ErrHandler class. We will now see how to use this Error Handler
class and handle errors at the page level as well as at the application
level.
Handling errors at Page Level
In
the Default.aspx, drag and drop a button from the toolbox. Rename this
button to btnError and set the Text as ‘Throw Handled Exception’. Here
we will throw an exception. Since we have a catch block defined, the
exception will be caught and the error will be logged in the Error
folder. Since a text file with today’s date, does not exists, a new
text file will be created by the code.
The button click handler will look similar to the following:
C#
protected void btnHandled_Click(object sender, EventArgs e)
{
try
{
throw new Exception("Sample Exception");
}
catch (Exception ex)
{
// Log the error to a text file in the Error folder
ErrHandler.WriteError(ex.Message);
}
}
VB.NET
Protected Sub btnHandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHandled.Click
Try
Throw New Exception()
Catch ex As Exception
' Log the error to a text file in the Error folder
ErrHandler.WriteError(ex.Message)
End Try
End Sub
Now
with the code in place, run the application and click on the button.
Since we have handled the error and logged the exception in our code,
you will not notice anything when the button is clicked. However, close
the application and refresh the Error folder. You will see a new text
file created with today’s date. The exception has been logged
successfully as shown below. The date and time will differ on your
machine.
Log Entry :
01/11/2008 23:33:46
Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception
__________________________
Redirecting users on unhandled errors
Let
us see how to catch unhandled errors and redirect the user to a
different page, whenever such an unhandled error occurs at the
application level.
To
catch unhandled errors, do the following. Add a Global.asax file (Right
click project > Add New Item > Global.asax). In the
Application_Error() method, add the following code:
C#
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error in: " + Request.Url.ToString() +
". Error Message:" + objErr.Message.ToString();
// Log the error
ErrHandler.WriteError(err);
}
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()
' Log the error
ErrHandler.WriteError(err)
End Sub
We
capture the error using the Server.GetLastError(). Now to redirect
users to a different page whenever an unhandled error occurs, open your
web.config file and locate the <customErrors> tag and uncomment
it. After removing the comment, the tag will look similar to the
following code:
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace. -->
<customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">
<errorstatusCode="403"redirect="NoAccess.htm" />
<errorstatusCode="404"redirect="FileNotFound.htm" />
</customErrors>
Now change:
mode="RemoteOnly"tomode="On"
defaultRedirect="GenericErrorPage.htm" to defaultRedirect="ErrorPage.aspx"
The modified code will now look like this:
<customErrorsmode="On"defaultRedirect="ErrorPage.aspx">
<errorstatusCode="403"redirect="NoAccess.htm" />
<errorstatusCode="404"redirect="FileNotFound.htm" />
</customErrors>
This
configuration will now redirect the user to an Error page when an error
occurs. Let us create this error page and display some message to the
user.
Right
Click Project > Add New Item> Create a new ErrorPage.aspx page in
the application and display a sample message on the page informing the
user that an error has occurred.
To
test our functionality, go back to Default.aspx, add another button and
rename it to btnUnhandled and set its Text property to ‘Throw Unhandled
Exception’. Here instead of throwing the exception as we did for
‘btn_Error’, we will introduce a ‘Divide By Zero’ exception and not
handle it. Observe that there is no try catch block as shown below. So
when the error occurs, the user will be redirected to the
‘ErrorPage.aspx’ as a result of the changes made in our web.config file.
C#
protected void btnHandled_Click(object sender, EventArgs e)
{
try
{
throw new Exception("Sample Exception");
}
catch (Exception ex)
{
// Log the error to a text file in the Error folder
ErrHandler.WriteError(ex.Message);
}
}
VB.NET
Protected Sub btnUnhandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUnhandled.Click
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i " j)
End Sub
Run
the application and click on the ‘Throw Unhandled Exception’ button.
You will observe that the user will be automatically redirected to the
Error Page and the error will be logged in the Error folder. Well
that’s it.
In
this article, we saw how to implement a simple error logging system in
our application. Logging errors can be very useful and helps us detect
errors during development and operation of a website. ASP.NET also
provides some advanced options titled under ‘Health Monitoring’ where
the errors can be stored in Sql Server or even emailed to the
administrator based on the criticality of it.
I hope this article was useful and I thank you for viewing it.
Download the source code of the application over here.