ASP. NET error logs and asp.net error logs
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:
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:
Void Application_Error (object sender, EventArgs e) {// code Exception objErr = Server when an unprocessed error occurs. getLastError (). getBaseException (); // record the IP address string strIP = Request. userHostAddress; string err = "Ip [" + strIP + "]" + Environment. newLine + "Error in [" + Request. url. toString () + "]" + Environment. newLine + "Error Message [" + objErr. message. toString () + "]"; // records the error FN. writeError (err );}
Configure the Web. Config file
<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.