ASP. NET error logging method

  • 2020-06-07 04:24:28
  • OfStack

In this article, we will document errors and exceptions in our website with a simple process. We do this by navigating the user to a separate page whenever a program error is encountered, and the error will be recorded to a text file on the server. Whenever an error occurs, we will log it daily.

First, I'll write a static method for logging error messages to a text file, in this case to the Error folder on the server
The code is as follows:


using System.Globalization;
    /// <summary>
    ///  Used to output error messages 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 file of the website Global.asax

void Application_Error(object sender, EventArgs e)
    {
        //  Code that runs when an unhandled error occurs 
        Exception objErr = Server.GetLastError().GetBaseException();
        // There is an error in the record IP address 
        string strIP = Request.UserHostAddress;
       string err = "Ip 【 " + strIP + " 】 " + Environment.NewLine + "Error in 【 " + Request.Url.ToString() +
                          " 】 " + Environment.NewLine + "Error Message 【 " + objErr.Message.ToString() + " 】 ";
        // Record the error 
        FN.WriteError(err);
    }

Configure the Web.Config file

<system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
     <!-- Additional error pages can be specified ...-->
    </customErrors>
    </system.web>

Create an GenericErrorPage.htm file for the error page that will be rendered if the user makes an error.


Related articles: