In this article, we will record errors and exceptions in our web site through a simple process. We do this, every time we encounter a program error, the user navigates to a separate page, while the error will be logged to a text file on the server, whenever the error occurs, we will log in the form of daily Records.
First, I'm going to write a static method to log the error message to a text file, where you can log the error message to the server's error folder
The code is as follows:
Copy Code code as follows:
Using System.Globalization;
<summary>
Used to output error information to 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 the Application_Error of the Web Global.asax file
Copy Code code as follows:
void Application_Error (object sender, EventArgs e)
{
Code that runs when an unhandled error occurs
Exception objerr = Server.GetLastError (). GetBaseException ();
Log the IP address where the error occurred
string StrIP = request.userhostaddress;
string err = "Ip" "+ StrIP +" "" + Environment.NewLine + "Error in" "+ Request.Url.ToString () +
"" + Environment.NewLine + "Error message" "+ objErr.Message.ToString () +" "";
Logging Errors
Fn. Writeerror (ERR);
}
Configuring Web.config files
Copy Code code as follows:
<system.web>
<customerrors mode= "RemoteOnly" defaultredirect= "genericerrorpage.htm" >
<!--can specify additional error pages ...-->
</customErrors>
</system.web>
Creates a genericerrorpage.htm file that is used for error pages that are rendered when an error occurs to the consumer.