Results 1 to 1 of 1

Thread: ASP.Net - How do I add logging to my Web Application using log4net?

  1. #1

    Thread Starter
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    ASP.Net - How do I add logging to my Web Application using log4net?

    The log4net assemblies can be found here:

    http://logging.apache.org/log4net/index.html

    log4net is a port of log4j specifically for use within .Net applications. It can equally be used for Windows Applications and Web Applications.

    The following steps detail what you need to do to add logging capabilities to your application.

    1. Download the log4net binary - http://logging.apache.org/log4net/download.html
    2. Extract the downloaded zip file
    3. In your application, add a reference to the following assembly:

      Code:
      incubating-log4net-1.2.10\log4net-1.2.10\bin\net\2.0\release\log4net.dll
    4. Open you web.config file and add the following node in the configuration | configSections node:

      vb.net Code:
      1. <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    5. Then, within the configuration node, and the following log4net configuration node:

      vb.net Code:
      1. <log4net>
      2.     <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      3.       <file value="Logs/Application.log" />
      4.       <appendToFile value="true" />
      5.       <immediateFlush value="true" />
      6.       <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      7.       <rollingStyle value="Size" />
      8.       <maximumFileSize value="10MB" />
      9.       <maxSizeRollBackups value="5" />
      10.       <layout type="log4net.Layout.PatternLayout">
      11.         <conversionPattern value="%newline[%date{dd MMM yyyy HH:mm:ss.fff}](%thread) %-5level: %message (%location)%newline" />
      12.       </layout>
      13.     </appender>
      14.     <root>
      15.       <level value="DEBUG" />
      16.       <appender-ref ref="RollingFileAppender" />
      17.     </root>
      18.   </log4net>

      The above node is fully configurable, and you will find numerous examples here. It is possible for instance to create multiple appenders, one for logging to a file, one for the System Event Log, log to an email address, etc. It really just depends on what you want to set up.

      The above simply creating a rolling log file, at Logs/Application.log. It allows a maximum log file size of 10MB and keeps 5 historical log files. I have also set the log level at DEBUG, meaning that I want all log messages to be recorded. In production servers, you can choose to reduce the amount written to the log file by changing this value to either WARN, INFO or ERROR.
    6. If you do not already have one, add a Global Application Class to your project (Right click on your project, select Add | New Item, then choose "Global Application Class" from the Templates, and leave the default name)
    7. Add the following import to the top of the Global.asax.cs:

      Code:
      using log4net;
    8. Declare the following private member:

      Code:
      private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
      This is the actual log instance that we will use to write out to our log file
    9. I typically add the following code, so that I get information about the application starting and stopping and sessions starting and stopping:

      Code:
              protected void Application_Start(object sender, EventArgs e)
              {
                  log4net.Config.XmlConfigurator.Configure();
                  log.Debug("Application Starting");
              }
      
              protected void Application_End(object sender, EventArgs e)
              {
                  log.Debug("Application Ending");
              }
      
              protected void Session_Start(object sender, EventArgs e)
              {
                  log.Debug("Session started");
                  log.DebugFormat("Session ID: {0}", HttpContext.Current.Session.SessionID);
              }
      
              protected void Session_End(object sender, EventArgs e)
              {
                  log.Debug("Session stopped");
                  log.DebugFormat("Session ID: {0}", HttpContext.Current.Session.SessionID);
              }
    10. At this point, we can start our application, and within the root folder of our application, you will find a Logs Folder, with an Application.log file, which contains the following lines (or very similar):

      Code:
      [15 Dec 2009 12:56:15.825](4) DEBUG: Application Starting (CS2008WebApplicationLog4netEnabled.Global.Application_Start(C:\temp\CS2008WebApplicationLog4netEnabled\CS2008WebApplicationLog4netEnabled\Global.asax.cs:18))
      
      [15 Dec 2009 12:56:18.215](4) DEBUG: Session started (CS2008WebApplicationLog4netEnabled.Global.Session_Start(C:\temp\CS2008WebApplicationLog4netEnabled\CS2008WebApplicationLog4netEnabled\Global.asax.cs:28))
      
      [15 Dec 2009 12:56:18.246](4) DEBUG: Session ID: twwth1fx5cus1mnftyeyrvvn (CS2008WebApplicationLog4netEnabled.Global.Session_Start(C:\temp\CS2008WebApplicationLog4netEnabled\CS2008WebApplicationLog4netEnabled\Global.asax.cs:29))


    What happens next, how do we add logging to the rest of our application?

    Well all you need to do is add the same using statement to each code file you want logging in, and also declare the private member for the log variable on each page, and away you go.

    You can expert with using:

    Code:
    log.Debug("Debug Message");
    log.Error("Error Message", ex);
    log.Fatal("Fatal Message", ex);
    log.Info("Info Message");
    log.Warn("Warn Message");
    Notice that it is possible to pass an exception to the methods as well. log4net will then write out the stack trace for you into the log file, which is very useful when debugging.

    Lesser known feauture

    One lesser known feature regarding log4net is that you can actually configure different log files for different portions of your application. Let's say you have the following namespaces in your application:

    Code:
    CS2008WebApplicationLog4netEnabled.BLL
    CS2008WebApplicationLog4netEnabled.DAL
    Where the first is your Business Level Logic, and the second is your data access layer. They may exist within the same assembly, but because of the separation of logic, you might actually want the log messages to also be separated. To achieve this, you can create two appenders, and only write the log messages from each namespace out to the correct appender. Here is an example configuration node where this is set up:

    vb.net Code:
    1. <log4net>
    2.     <appender name="RollingFileAppenderDAL" type="log4net.Appender.RollingFileAppender">
    3.       <file value="Logs/BLL.log" />
    4.       <appendToFile value="true" />
    5.       <immediateFlush value="true" />
    6.       <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    7.       <rollingStyle value="Size" />
    8.       <maximumFileSize value="10MB" />
    9.       <maxSizeRollBackups value="5" />
    10.       <layout type="log4net.Layout.PatternLayout">
    11.         <conversionPattern value="%newline[%date{dd MMM yyyy HH:mm:ss.fff}](%thread) %-5level: %message (%location)%newline" />
    12.       </layout>
    13.     </appender>
    14.  
    15.     <appender name="RollingFileAppenderDAL" type="log4net.Appender.RollingFileAppender">
    16.       <file value="Logs/DAL.log" />
    17.       <appendToFile value="true" />
    18.       <immediateFlush value="true" />
    19.       <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    20.       <rollingStyle value="Size" />
    21.       <maximumFileSize value="10MB" />
    22.       <maxSizeRollBackups value="5" />
    23.       <layout type="log4net.Layout.PatternLayout">
    24.         <conversionPattern value="%newline[%date{dd MMM yyyy HH:mm:ss.fff}](%thread) %-5level: %message (%location)%newline" />
    25.       </layout>
    26.     </appender>  
    27.    
    28.     <root>    
    29.     </root>
    30.  
    31.     <logger name="CS2008WebApplicationLog4netEnabled.BLL" additivity="false">
    32.       <level value="DEBUG" />
    33.       <appender-ref ref="RollingFileAppenderBLL" />
    34.     </logger>
    35.  
    36.     <logger name="CS2008WebApplicationLog4netEnabled.DAL" additivity="false">
    37.       <level value="DEBUG" />
    38.       <appender-ref ref="RollingFileAppenderDAL" />
    39.     </logger>
    40.   </log4net>

    Notice, that the two appenders are specifically filtered to look only for log messages that come from the different namespaces of your application
    Last edited by gep13; Jul 17th, 2011 at 06:07 AM. Reason: Added HIGHLIGHT tags to get over issue with XML not showing up

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width