Loading ...

How to use log4net in ASP.NET | CodeAsp.Net

How to use log4net in ASP.NET

(34117)
3.76
/5
Avg: 3.76/5: (2 votes)
Published: 4/3/2013 by Raghav Khunger

What is log4Net?

The Apache log4net library is a means to help the programmers output assertions or logs to a variety of output targets. It is very helpful in the cases where you are facing problems with an application and want to log statements to locate the problem. The statements are logged with the help og log4Net during the runtime of the program.
 
From where to download it?
You can download the log4Net dll from the Apache logging services Download Apache log4net™ 1.2.10 Download the log4Net.dll from the mentioned link and put it in your bin folder.

What can we do with log4Net?

Log4Net is a logging framework whose API meant to be used within your application (web, console, dll, etc.). We can use it like below:

logger.Debug("Some low level debug message...");
logger.Info("Some basic info");
logger.Warn("Some business logic problem, but not critical");
logger.Error("An unexpected error");

i.e depending upon what kind of level we want to log we can call debug, info, warn and error methods of logger instance. Various kinds of information can be logged via one or more loggers. The loggers provided by log4Net are:

  • Debug
  • Information
  • Warnings
  • Error
  • Fatal

How to use it with ASP.NET?

Step 1: Add the reference of log4Net.dll to your project.

 

Step 2: Add a new config file at the root of your solution and name it log4Net.config.
Instead of writing the config settings for log4Net in webconfig itself I will explain how we can keep the log4Net config settings in a separate config file so as to avoid the tight coupling of web config. Below is the source of log4Net.config file:  

<?xml version="1.0"?>

<log4net debug="true">
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
    <param name="File" value="Logs\\Log4Net.log"/>
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="10" />
    <maximumFileSize value="10MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
    </layout>
  </appender>
  <logger name="File">
    <level value="All" />
  </logger>
  <root>
    <level value="All" />
    <appender-ref ref="LogFileAppender" />
  </root>
</log4net>

Step 3 : Note the path of the file in the above config where information will be logged. Add a new folder named Logs at the root of your solution. Add a new text file named Log4Net.txt inside that folder.



Position of log4Net.config and Logs folder in the solution:



Step 4: Add the log4Net intializer code in Global.asax

You need to add the following code in the Application_Start event of Global.asax.cs:

   string l4net = Server.MapPath("~/log4net.config");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));

Below is the complete code of Global.asax.cs of my side while creating this sample:

using System;

namespace Sample
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            string l4net = Server.MapPath("~/log4net.config");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}

We are done here in setting up of log4Net. Now it's the time to use it.

Usage:
Let's create a sample page say default.aspx. We need to have the logger instance here first. We can get that via this code:

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

Now we can use this logger instance to log the statements we want to. Below is the complete code of default.aspx.cs:

using System;
using log4net;

namespace Sample
{
    public partial class _Default : System.Web.UI.Page
    {
        private static ILog logger =
            LogManager.GetLogger(
                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        protected void Page_Init(object sender, EventArgs e)
        {
            logger.Info("I am in Page Init");

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            logger.Info("I am in Page Load");

        }
    }
}

After running the above page our information which we wanted to log has been logged in the Logs\\Log4Net.text file. Below was the output at my side after running the page:

That's it we are done with the basic use of log4Net with ASP.NET. That was the basic and simplest usage what I could explain to let you understand the setup of log4Net and using it with ASP.NET. The log4Net has much more options which you can configure via config file. For more reference you can refer Apache log4net™ Features

Vijendra Shakya, Raghav Khunger and 2 others like this.
 

Comments (4)

gajtan
Just a side note: Among many log4net appenders, it's good to know that you can add TelnetAppender - Appender that allows clients to connect via Telnet to receive log messages - I find it useful for monitoring
7/9/2012
 · 
 
by
.net  pro
.net pro said:
Informative post on Log4net. You presented it clearly and briefly. Good work Raghav
1/2/2013
 · 
 
by
eduardo
eduardo said:
Great!Great!Great!Great!Great!Great!Great!

Most of articles that i look it was doing strange things like add a assembly file to webapp. You show very clear how use a separate file with log4net.

thank you
2/27/2014
 · 
 
by
Grandit
Grandit said:
I just want to write one thing.....thank you!
Like eduardo just said - very clear.
3 days ago
 · 
 
by
  • Name:*
  • Email:*
  • Website:
Type the characters you see in the image *

Top articles

Quick Vote

What kind of email newsletter would you prefer to receive from CodeAsp.Net?