ASP.Net Global.asax Simple Error Logger

RSS
Modified on 2011/11/30 19:29 by Mark Categorized as aspNet, csharp, dotNet, web
Simple Exception Logging block in C#.

   void Application_Error(object sender, EventArgs e)
   {
      // Code that runs when an unhandled error occurs
      Exception exc = Server.GetLastError();

      StringBuilder bldr = new StringBuilder();
      try
      {
         bldr.AppendLine(DateTime.UtcNow.ToString("o"));
         bldr.AppendLine(exc.ToString());
         bldr.AppendLine("");
         System.IO.File.AppendAllText(Server.MapPath("~/errors.txt"), bldr.ToString());
      }
      catch (Exception e2) { /*Response.Write("<p>" + HttpUtility.HtmlEncode(e2.ToString()) + "</p>"); */}
            

      if (exc.GetType() != typeof(HttpException))
      {
         // For other kinds of errors give the user some information
         // but stay on the default page
         Response.Write("<h2>Oops</h2>\n");
         Response.Write(
             "<p>An error occurred.</p>\n");
         Response.Write("Return to the <a href='Default.aspx'>" +
             "Default Page</a>\n");

         // Log the exception and notify system operators
         //ExceptionUtility.LogException(exc, "DefaultPage");
         //ExceptionUtility.NotifySystemOps(exc);

         // Clear the error from the server
         Server.ClearError();
      }

   }

See Also