log4net: How To

Configurations that go into the configuration tag in the Web.Config(File Appender)

<configuration>

   <configSections>

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

    </configSections>

              <log4net debug=”false”>

             <appender name=”LogFileAppender” type=”log4net.Appender.FileAppender,log4net” >

                  <param name=”File” value=”D:LogRTS-log.txt” />

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

                            <layout type=”log4net.Layout.PatternLayout,log4net”>

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

                         </layout>

                     </appender>

                     <root>

                        <priority value=”DEBUG” />

                         <appender-ref ref=”LogFileAppender” />

                     </root>

             </log4net>……

 

 Initialize the loggers configurations in Global.asax 

protected void Application_Start(Object sender, EventArgs e)

   {

        log4net.Config.DOMConfigurator.Configure();

   }  

 Using the logger in a page

private static ILog log = LogManager.GetLogger(typeof(SLK.RTS.Web.UI.Review.ReviewersFeedback));

private void Upload()

{

    try

       {

              throw new Exception();

       }

       catch(Exception ex) {

                 log.Fatal(“Upload failed” + ex.Message);

                 log.Info(ex.Message);

                  log.Debug(ex.StackTrace);

       }

}

  Catching all logger exceptions

protected void Application_Error(Object sender, EventArgs e){   

        const string strUserId = “User Id : {0};n”;

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

        if(log.IsFatalEnabled) log.Fatal(String.Format(strUserId,Utility.AppContext.UserId.ToString()),ex);   

        if (log.IsInfoEnabled)log.Debug(ex.StackTrace);

        if (log.IsInfoEnabled) log.Info(“n———————————————-n”);

}