Wednesday, 9 April 2014

Use of log4net Logging Mechanism in C#

DLL Used : log4Net 1.2.13

App.Config File Settings
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
  </configSections>

  <!--<log4net.dll Configuration Settings Date : 09/04/2013>-->
  <log4net>
    <!--<Appender for Info and Error logging>-->
    <appender name="LogInfoFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="D:\\StudentDataLog.txt"/>
      <!--<Please specify the file with path here for log file>-->
      <param name="AppendToFile" value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="2"/>
      <maximumFileSize value="10MB"/>
      <staticLogFileName value="true"/>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p – %20C %20M %m%n%n"/>
      </layout>
    </appender>

    <root>
      <level value="ALL"/>
      <appender-ref ref="LogInfoFileAppender"/>
    </root>


  </log4net>
</configuration>

In cs file
using log4net.Layout;
using log4net;

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


public StudentInformation()
{
    InitializeComponent();
    log4net.Config.XmlConfigurator.Configure();
}

public void SaveInformation()
{
   log.Info("Revanayya Hiremath");
   log.Info("2BA10MCA15");
   log.Info("Mahesh Datta");
   log.Info("084GE08CS020);
}

Possible Errors while running in VS 2010
The namespace or namespace name 'log4net' could not be found
If you have added a reference to log4net correctly and added your usings, you may get a compile error “The type or namespace name ‘log4net’ could not be found (are you missing a using directive or an assembly reference?)”.


This is most likely due to the Target framework being set to .NET Framework X Client Profile. Change this to .NET Framwork 4 (full version) and your application will compile.




IsDebugEnabled, IsErrorEnabled, IsFatalEnabled is flase

Before:


After:    
Use below code before writing the log  

log4net.Config.XmlConfigurator.Configure()

1 comment: