In this article, we will record errors and exceptions on our website through a simple process. In this way, when a program error occurs, the user is redirected to a separate page, and the error is recorded in a text file on the server. When an error occurs, we will record the log every day.
First, I will write a static method to record the Error information to a text file. Here, I will record the Error information to the Error folder on the server.
The Code is as follows:
Copy codeThe Code is as follows: using System. Globalization;
/// <Summary>
/// Output error information to the txt file
/// </Summary>
/// <Param name = "errorMessage"> error details </param>
Public static void WriteError (string errorMessage)
{
Try
{
String path = "~ /Error/"+ DateTime. Today. ToString (" yyMMdd ") +". 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 ));
W. WriteLine (errorMessage );
W. WriteLine ("________________________________________________________");
W. Flush ();
W. Close ();
}
}
Catch (Exception ex)
{
WriteError (ex. Message );
}
}
Add the following code to Application_Error in the Global. asax file of the website:Copy codeThe Code is as follows: void Application_Error (object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception objErr = Server. GetLastError (). GetBaseException ();
// Record IP addresses with errors
String strIP = Request. UserHostAddress;
String err = "Ip [" + strIP + "]" + Environment. NewLine + "Error in [" + Request. Url. ToString () +
"]" + Environment. NewLine + "Error Message [" + objErr. Message. ToString () + "]";
// Record errors
FN. WriteError (err );
}
Configure the Web. Config fileCopy codeThe Code is as follows: <system. web>
<CustomErrors mode = "RemoteOnly" defaultRedirect = "GenericErrorPage.htm">
<! -- Other error pages can be specified... -->
</CustomErrors>
</System. web>
Create a genericerrorpage.htm file for the error page displayed by the user when an error occurs.