Header Ads

Log4Net Tutorial in C# .net (How can I show log in a file?)

log4net:
For logging service my choice is log4net from Apache Software Foundation. It is easy to use, open source and well documented. There are also so many logging services but they are not open source. So it is an easy and best solution for you.

Write Log in procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create a new website.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. write the main method like this

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using log4net;
using log4net.Config;
using log4net.Core;
using log4net.Repository.Hierarchy;
using log4net.Appender;
using System.Collections.Generic;
using System.Xml.Schema;
public partial class _Default : System.Web.UI.Page
{

  protected void Page_Load(object sender, EventArgs e)

  {

  }

  protected void btn_Click(object sender, EventArgs e)

  {

      int a = 23, b = 0;
              try

              {



                  int result = a / b;



              }



              catch (Exception ex)

              {



                  // Divide by Zero exception occurred and in the next line we are going to log tha

               log4net.ILog log =log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

               log4net.Config.XmlConfigurator.Configure();

                 log.Debug(ex.Message);

                  log.Error(ex.Message);

                  log.Warn(ex.Message);

                  log.Info(ex.Message);

                  log.Fatal(ex.Message);



              }

          }

}

5.Now put this web.config/app.config file in configuration tag.

<configsections>

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

</section>

<log4net>

<root>

<level value="DEBUG">

<appender-ref ref="LogFileAppender">

</appender-ref>

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

<param name="File" value="C:\ErrorLogFile\log.txt">

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

<rollingstyle value="Size">

<maxsizerollbackups value="10">

<maximumfilesize value="10MB">

<staticlogfilename value="true">

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

<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} â�� %m%n">

</layout>

</staticlogfilename>

</maximumfilesize></maxsizerollbackups></rollingstyle></appender></level></root></log4net></configsections>


If you run this code log file show in the C:\ErrorLogFile\log.txt


Powered by Blogger.