static void

ASP Error Handling

With log4net. See more

Web.config (log4net)

<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    </configSections>
    <log4net>
        <appender name="File" type="log4net.Appender.RollingFileAppender">
            <file value="log4net.log"/>
            <appendToFile value="true"/>
            <rollingStyle value="Date"/>
            <datePattern value="yyyyMMdd"/>
            <layout type="log4net.Layout.PatternLayout">
              <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline"/>
            </layout>
        </appender>
        <root>
            <level value="ERROR"/>
            <appender-ref ref="File"/>
        </root>
    </log4net>

Global.asax

void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
    Exception ex = HttpContext.Current.Server.GetLastError();
    if (ex != null)
        ErrorHandler.HandleException(ex);
}
 
void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    log4net.Config.XmlConfigurator.Configure(); //comment this to stop logging
}

Error Logging class

From: ASP.NET 2.0 Anthology, 2007.

using System;
using System.Reflection;
using System.Text;
using System.Web;
using log4net;
 
public static class ErrorHandler
{
    private static readonly ILog Log = LogManager.GetLogger(typeof(ErrorHandler));
 
    public static void HandleException(Exception ex)
    {
        if (ex == null) return;
        Exception exceptionLayer = null;
        if (ex is HttpUnhandledException)
        {
            if (ex.InnerException != null)
                exceptionLayer = ex.InnerException;
        }
        else
            exceptionLayer = ex;
 
        StringBuilder sb = new StringBuilder();
        while (exceptionLayer != null)
        {
            sb.AppendLine(ex.ToString());
            sb.AppendLine("------------------------");
            exceptionLayer = exceptionLayer.InnerException;
        }
        Log.Error(sb.ToString());
    }
}

Quick text logging (no log4net)

private void SaveError()
{
    Exception lastError = Server.GetLastError();
    if (lastError == null) return;
    if (lastError.InnerException != null)
        lastError = lastError.GetBaseException();
 
    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("~/error.txt"), true))
    {
        sw.WriteLine("{0} [{1}] {2}", DateTime.Now, lastError.Message, lastError.GetType());
        sw.WriteLine(lastError.StackTrace);
    }
}