Showing posts with label log4net. Show all posts
Showing posts with label log4net. Show all posts

Thursday, March 22, 2012

Part 2 : How to use log4net in .net


In Part 1 : How to use log4net in .net you have learnt the basic of log4net. Here I am going to tell you some more details about it.

Create Date based log file

Yes, you can also create your log files date vise. If you want to create a separate file for every day then you can also do that in the log4net. You need to set the <staticLogFileName value="false">
 in the appender.
 The appender section will be

  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="d:\"/>
      <staticLogFileName value="false"/>
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyy-MM-dd'.log'" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
  </appender>

Here the value of the file section specify the path of the log file. I have specify the "D:\ "then the file will be created in the "D" drive. If you specify the "d:\log_" then the log file will be "log_2012-03-22.log".


Create separate log file for specified log level

Here I would like to let you know how you can log the information according to their log level (Debug, Info, Warning, Error, Fatal) in different files. For example, if you want to log Debug log into a file and Error log to another file, you can achieve this through the log4net. For that you just have to add the two appender according to their log level. Each appender will have different log file.

<appender name="ErrorLogFileAppender" type="log4net.Appender.FileAppender">
<param name="File"value="D:\ErrorLogFile.txt"/>
<param name="AppendToFile" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
</layout>
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="ERROR"/>
</filter
<filter type="log4net.Filter.DenyAllFilter" />
</appender>
    <appender name="DebugLogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="D:\DebugLogFile.txt"/>
<param name="AppendToFile" value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
</layout>
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="DEBUG"/>
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="DebugLogFileAppender" />
<appender-ref ref="ErrorLogFileAppender" />
</root>
 
Here I have created two appender ErrorLogFileAppender and DebugLogFileAppender. ErrorLogFileAppender logs the Error level log and store the log information into the ErrorLogFile.txt and DebugLogFileAppender logs the Debug log and store the log information into the DebugLogFile.txt.


Appenders

We can log the information into differenct destination output through the Appender.  In Previous examples we have seen the FileAppender which is used to log the information into a file. However, log4net provides numbers of Appenders to log the information, you can customized as per your need.

FileAppender
                See the previous examples.


SmtpAppender
 SmtpAppender is used when you want to get the specified event log through the email. The following example will show how to use the SmtpAppender.

    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <to value="to@domain.com" />
      <from value="from@domain.com" />
      <subject value="my logging message" />
      <smtpHost value="SMTPServer.domain.com" />
      <bufferSize value="512" />
      <lossy value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
      </layout>
    </appender>

 Here to specifies the address where log event should be send. The from is the address from which account email should be send. The subject specifies the subject of the email. You can also customise this subject. The bufferSize specifies the size of the email. As soon as log event information reached that size, it sends the email.

<subject type="log4net.Util.PatternString" value="%property{log4net:HostName} Error: %appdomain" />

Here I have customised the subject. The HostName and appdomain represents the your host name and application domain of your application.

In the above appender all the log events will be sent to the specified email address, however you can also mentioned which log event you want in email. For that you have to use the following configuration.

<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">     
<to value="to@domain.com" />     
<from value="from@domain.com" />     
<subject value="my logging message" />     
<smtpHost value="SMTPServer.domain.com" />     
<bufferSize value="512"/>     
<lossy value="true" />     
<evaluator type="log4net.Core.LevelEvaluator">       
<threshold value="ERROR"/>     
</evaluator>      
<layout type="log4net.Layout.PatternLayout">       
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />     
</layout>
</appender>
 
Here you will get only Errro log event through the email. For that you have to set the lossy to "true" and evaluator to "ERROR".

ConsoleAppender
 Basically ConsoleAppender is used to show the log event information into the console output. The following configuration is used for the ConsoleAppender.

 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"/&agt;     
<layout type="log4net.Layout.PatternLayout"/&gt       
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />     
</layout>    </appender>
   

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.