How To Easily Add Log4Net To Your .NET Project

  1. Download Log4Net binaries –>  http://logging.apache.org/log4net/download_log4net.cgi
  2. Add Reference to Log4Net.dll in your project
  3. Create new “Logs” folder and ensure Web App/Site has Write privileges to this directory
  4. Add the following to Global.asmx
     
        /// <summary>
        /// Gets the application log4net log instance.
        /// </summary>
        /// <value>The log.</value>
        public ILog log
        {
            get { return LogManager.GetLogger("AppLogger"); }
        }
    
        void Application_Start(object sender, EventArgs e) 
        {
            // Code that runs on application startup
            log4net.Config.XmlConfigurator.Configure();        
    
        }
        
    
  5. Add Log4Net config section and declaration into web.config/app.config
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
      </configSections>
      <appSettings>   
      </appSettings>
      <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
          <file value="Logs/application.log"/>
          <appendToFile value="true"/>
          <rollingStyle value="Composite"/>
          <datePattern value="yyyyMMdd"/>
          <maxSizeRollBackups value="10"/>
          <maximumFileSize value="5MB"/>
          <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%n DATE: %date{MM/dd/yyyy HH:mm:ss} %n THREAD: [%thread] %n LEVEL: %-5level %n USER ID: %identity %n CLASS: %type{1} %n METHOD: %M %n LOCATION: %location %n MESSAGE: %message %n "/>
          </layout>
        </appender>
        <root>
          <level value="DEBUG"/>
          <appender-ref ref="LogFileAppender"/>
        </root>
      </log4net>
    </configuration>
    
  6. Add private static readonly property referencing ILog
      class Program
        {       
            /// &lt;summary&gt;
            /// Logging
            /// &lt;/summary&gt;
            //private readonly ILog Logger = DecisionLogManager.GetLogger(typeof(UC4Request));    
          private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
  7. Call Error method to log error
     
                catch (Exception ex)
                {
                    // Log to local log file
                    log.Error("Error", ex);
                }
    
  8. You can also call other methods (Info) to output debug information
     
             log.Info(responseOutput +
                             Environment.NewLine +
                             Base.HelperFunctions.ObjectToString(keywordClientReply, DisplayMode.HTML)
                             );
    
Advertisements

More Verbose Application_Error() handling in global.asx

Extracting exception specifics like line number, class, method, etc:

   /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {     
            try
            {  
                Logging logging = new Logging();

                Exception ex = Server.GetLastError().GetBaseException();

                StackTrace trace = new StackTrace(ex, true);                

                string sourceFile = trace.GetFrame(0).GetFileName();
                int sourceLine = trace.GetFrame(0).GetFileLineNumber();
                string sourceMethod = trace.GetFrame(0).GetMethod().Name;            
                string sourceClass = trace.GetFrame(0).GetMethod().DeclaringType.ToString();
                string sourceMessage = ex.Message.ToString();
                string sourceThreadID = AppDomain.GetCurrentThreadId().ToString();

                string currentUser = (SessionWrapper.CurrentLoggedInUser != null) ? SessionWrapper.CurrentLoggedInUser.UserId : "";

                logging.insertLog(sourceClass, DateTime.Now,
                    trace.ToString(), currentUser, "FATAL",
                    sourceLine.ToString(), sourceMessage, sourceMethod, sourceThreadID, 0, 0, currentUser, "EHAP");

            }
            catch (Exception)
            {
                // If logging to database fails, log to file system
                log.Fatal("EHAP Site Application_Error", Server.GetLastError());

            }
          

            Response.Redirect("/SiteException.aspx", false);
            System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
            Server.ClearError();

        }

Global ASP.NET Application Error Logging With Log4Net

In your UI project’s Global.asax.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using log4net;



namespace YourNameSpace
{
    public class Global : System.Web.HttpApplication
    {

        /// <summary>
        /// Gets the log.
        /// </summary>
        /// <value>The log.</value>
        public ILog log
        {
            get { return LogManager.GetLogger("YourAppNameLogger"); }
        }


        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
        
        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            log.Fatal("Site Application_Error", Server.GetLastError());
            Response.Redirect("/SiteException.aspx", false);
            System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
            Server.ClearError();
        }


    }
}

Create SiteException.aspx :

<div id="error">
        <img alt="Error Symbol" src="Images/error.png" />
        <p>
            We're sorry but an error was encountered while processing your request.
        </p>
        <p>
            Please try submitting your request again.</p>
        <p>
        </p>
        <p>
            If the problem persists please contact the administrators at 000.000.0000</p>
    </div>

And you can test this in a page by doing the following in a dummy test page:

 public partial class Default : System.Web.UI.Page
    {
        void Page_Load(object sender, System.EventArgs e)
        {
           // test global error handling
            throw (new ArgumentNullException());

        }
    }

It should redirect you to the SiteException.aspx page as an error was thrown.