Saturday, February 18, 2012

Part 1 : How to use log4net in .net

Introduction


This article describes how to use the log4net for the .net application. Log4net is the open source library used to log the application event message in the different sources. You can log the info into the file, console output, event log or can be send in the email. The main advantage to use this, it's flexibility and extendenbility. You can control the log though the configuration file without change the code. Here I am going to give you the overview how to use the log4net for the asp.net web application.


You just have to create an asp.net website, changed in the web.config file and call the log method.


Steps:


1.      Download the latest dll file of log4net from the link here 

2.      Create the asp.net website, and add the reference of log4net.dll to this application.

3.       Add the following section in the  <configSections>   section of the web.config file


  
  <configSections>
     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>                  
 < configSections>



      4.  Then add the following section in the the  <configSections>  section



  <log4net>

      <appender name="LogFileAppender" type="log4net.Appender.FileAppender">

      <param name="File" value="D:\LogFile.txt"/>

      <param name="AppendToFile" value="true"/>

      <layout type="log4net.Layout.PatternLayout">

        <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>

       </layout>
       </appender>
    <root>

      <level value="DEBUG"/>

      <appender-ref ref="LogFileAppender"/>

    </root>
 </log4net>


Here <log4net>  contains to more sub sections <appender> and <root> Appender specify what type of log to be logged, where it should be logged, how you need to log and what type of information you want to log. Here I have used file appender. The Name of the appender can be anything. The type for the file logger should be log4net.Appender.FileAppender. You can also extend the class as per your need. The "D:\LogFile.tx" specify the file path where it should be logged. specify the log information format. You can also customized this format. The section is used to specify the appender reference and define what level of log you want to logged.


   5.Add the namespace in the default.aspx.cs page




  using log4net;

  using log4net.Config;


  6. Add the following code in the Page_Load method




  private static readonly ILog logger = LogManager.GetLogger(typeof(_Default));



OR




 private static readonly ILog logger =       LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)



   7. Add the following code in the Page_Load method



 protected void Page_Load(object sender, EventArgs e)

  {

     DOMConfigurator.Configure();

    try

    {

       int a = 0, b = 1;

       logger.Debug("Log Debug");

       logger.Info("Log info");

       logger.Warn("Log Warn");

       logger.Fatal("Log Fatal");

      float c = b/a;
    }

    catch (Exception ex)

    {

      logger.Error("some errro in the application ",ex);

    }

  }


  7. Run the application.


  8. Now open the LogFile.txt. The output will be




  2012-02-18 13:58:01,197 [2348] DEBUG _Default Log Debug

  2012-02-18 13:58:01,203 [2348] INFO _Default Log info

  2012-02-18 13:58:01,203 [2348] WARN _Default Log Warn

  2012-02-18 13:58:01,203 [2348] FATAL _Default Log Fatal

  2012-02-18 13:58:01,219 [2348] ERROR _Default some errro in the application

  System.DivideByZeroException: Attempted to divide by zero.

  at _Default.Page_Load(Object sender, EventArgs e) in d:\Log4NetWeb\Default.aspx.cs:line 31



Disable log4net


 The big benefit of using the log4net is, you can configure it without changing the code. Once you have completed your code and published the application, then you can change the configuration through the configuration section of the .config file. If you want to disable the log4net then you just need to add the <threshold> section in the appender section. 


      <appender name="LogFileAppender" type="log4net.Appender.FileAppender">

        <threshold value="OFF" />

       <param name="File" value="D:\LogFileInfo.txt"/>

       <param name="AppendToFile" value="true"/>

       <layout type="log4net.Layout.PatternLayout">

         <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>

       </layout>

     </appender>     


Specify log level


You can use 7 type of levels in the logging. These levels specify what kind of log you want to add into your application.


1. ALL

2. Debug

3. Information

4. Warning

5. Error

6. Fatal

7. OFF


The sequence is very important here. ALL specify that all kind of logs will be loged. If you specify Debug then all types of log can be logged. If you specify Information then all the log will be logged except Debug and if you specify Fatal then only Fatal log. OFF type of level will not log any kind of log.  These level are specify in the >

    <root>
      <level value="DEBUG"/>

      <appender-ref ref="LogFileAppender"/>

    </root&gt;



Filters


Filter is the another kind of criteria which tell what kind of level you want to log. Filter is specified in the appender. You can use multipal appender in the same logger and each appender can contain different Filters. As per the name, Filter filters the log information or log the information as per the filter criteria. There are different types of Filters:


StringMatchFilter


This Filter check if the matching string is exist in the log or not. If exist then log the information otherwise does not log.


      
      <filter type="log4net.Filter.StringMatchFilter">
        <stringToMatch value="Pankaj" />
      </filter>

      <filter type="log4net.Filter.DenyAllFilter" />


Here I have used the Filter section and used the StringMatchFilter filter. It will log only those information which has string "Pankaj". You also have to add the section    <filter type="log4net.Filter.DenyAllFilter" /> . Now I have changed the above code.



    protected void Page_Load(object sender, EventArgs e)
    {

        DOMConfigurator.Configure();

        try

        {

            int a = 0, b = 1;

            logger.Debug("Log Debug");

            logger.Info("Log info");

            logger.Warn("Log Warn");

            logger.Fatal("Pankaj Log Fatal");

            float c = b/a;

        }

        catch (Exception ex)

        {

            logger.Error("some errro in the application ",ex);

        }       

    }




If you don’t include the DenyAllFilter  section then it will log all the log (DEBUG, INFO, WARN, FATAL, ERROR). DenyAllFilter section will deny all the log and stringToMatch log only those information who has the string "Pankaj".


LevelMatchFilter


When you need to log only specified level of log then you can use LevelMatchFilter. For example, if you want to log only ERROR level then the syntax will be




    <filter type="log4net.Filter.LevelMatchFilter">

           <levelToMatch value="ERROR"/>
    </filter>
   <filter type="log4net.Filter.DenyAllFilter" />


LevelRangeFilter


This type of logging is basically used when you need to log a specified range of log. For example, if you want to log only those information which are between the WARNING and FATAL, then the systax will be


    
  <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="WARN" />
        <levelMax value="FATAL" />
   </filter>



Now if you run the  Page_Load  function then only WARN, ERROR and FATAL will be logged, not DEBUG and INFO.


1 comment:

  1. Are you looking to make cash from your websites with popup advertisments?
    If so, have you tried using PropellerAds?

    ReplyDelete