Header Ads

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

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.

Log4Net Tutorial in C#

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;


                  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);










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


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




<level value="DEBUG">

<appender-ref ref="LogFileAppender">


<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">




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