CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Exception or Error Logging in Asp.Net Using log4net – PART 1

By Bala Murugan
Posted On May 20, 2012
Article Rating:
Be first to rate
this article.
No of Comments: 3
Category: ASP.Net
Print this article.

Exception/Error Logging in Asp.Net Using log4net – PART 1

Logging is one of the most inevitable parts of any application we develop. Any application when deployed to production should have a proper logging framework that can log the errors to a viable source in order to get more information about the error for debugging purposes. Since, errors can occur at any place of our application the logging framework should be designed and developed with care to prevent any repercussion it may cause to the application due to the fact that the logging code will be scattered around the application. There are some good alternatives to writing our own logging framework since it requires some development effort. Microsoft released its own logging framework as part of enterprise library application block. Another very useful and simple logging framework is log4net from the open source community. In this article, we will see how to integrate and use log4net logging framework in ASP.Net applications.

Pre-Requisites

To understand this article, create a new ASP.Net site with the language of your choice in your Visual studio 2010. I have used C# in this article. Now, download the latest version of log4net from its official site. The latest version is 1.2.11 at the time of this writing. You can download the zip file with new key as advised in the site. Unzip the file and you can find the dll in the folder log4net-1.2.11-bin-newkey\log4net-1.2.11\bin\net for each framework version. We will use the one in 4.0 folder for this article. Add reference to the dll in your solution explorer. Please note that you can use Nuget package manager also to get the log4net integrated in your application.

Before moving to actual implementation it will be better to know some of the basics of log4net framework to better understanding.

 

log4net framework

The log4net framework has 3 main components: logger, appender and layout. A logger is the one which actually logs the error to a log destination with the help of an appender. There are different types of appenders available that writes to different sources. For example, Event log, a database table, a text file, emails, etc. The layout component will define the structure or format of the actual logs message that is logged.

The loggers can be assigned with various levels which dictate if it should log or not to log a message. The levels have a priority as specified below,

1.      ALL

2.      DEBUG

3.      INFO

4.      WARN

5.      ERROR

6.      FATAL

7.      OFF

 

All these levels except ALL and OFF have an equivalent logging method defined in the logger to log the message for each level.

1.      void Debug(object message);

2.      void Info(object message);

3.      void Warn(object message);

4.      void Error(object message);

5.      void Fatal(object message);

 

When you set a logger to a priority level “ALL” then it will log all the messages you specified in your code regardless the levels i.e. it will log all the message in debug, info, warn, error, fatal methods. A logger with priority level set to “Error” will log only the messages in Error and Fatal logger methods. Similarly, if the logger level is set to OFF then no messages with be logged. The below simple table will help you understand what gets logged for each priority level.

Logger Method

ALL

DEBUG

 

INFO

 

WARN

 

ERROR

 

FATAL

 

OFF

Debug(object message)

x

x

 

 

 

 

 

Info(object message)

x

x

x

 

 

 

 

Warn(object message)

x

x

x

x

 

 

 

Error(object message)

x

x

x

x

x

 

 

Fatal(object message)

x

x

x

x

x

x

 

 

Configuring Logging

To configure logging using log4net in your Asp.Net application you first need to configure an Appender with a Layout format defined and a Logger in Web.config.

As a first step, register the config section named log4net in <configSections> of your web.config.

  <configSections>

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

  </configSections>

 

Assuming we need to log the exceptions to EventLog destination the configuration will be,

 

<log4net>

  <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >

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

        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

      </layout>

    </appender>

 

    <root>

      <level value="ALL"/>     

      <appender-ref ref="EventLogAppender"/>

    </root>   

</log4net>

 

The above section should be configured outside <system.web> element. The above setting configures a default logger called root logger which will capture any log message raised in the code. You can also create logger explicitly by naming them apart from creating a default logger which is demonstrated in next part of this article.  The default logger is set to a level “ALL” which means the logger will log all the messages raised in the application.

 

Just for demonstration purpose I will create a divide by zero exception and log it using log4net logger methods. See below,

public partial class _Default : System.Web.UI.Page

{

    private static readonly ILog log = LogManager.GetLogger(typeof(_Default));

 

    protected void Page_Load(object sender, EventArgs e)

    {

        int n1 = 10;

        int n2 = 0;

      

        double result2 = n1 / n2;

 

        Response.Write(result2.ToString());

    }

    public void Page_Error(object sender, EventArgs e)

    {      

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

        log.Fatal(objErr.Message, objErr);

    }

}

 

When executed, the above code will log the exception to Event Log as seen in below figure.

Exception handling and logging using log4net in EventLog

 

In the code, we can obtain the logger object using the static method GetLogger(Type/Name) in LogManager class. Here the log4net creates a logger with name _Default (codebehind class name) when we call LogManager.GetLogger(typeof(_Default)) in the above code. The logger names are usually appended in the log message which will helps us to identify the place where the exception occurred easily. For example, _Default in the above figure hints the exception occurred in _Default object. If the exception is occurred in some other class then the name of the class specified as fully qualified name as logger name will occur in the log message which hints us the exception location.

 




Logging to a flat file (Rolling file Appender)

The below configuration will log the exceptions to a text file.

<log4net>

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

      <file value="D:\Technicals\Log4Net\Logs\example.log"/>

      <appendToFile value="true"/>

      <maximumFileSize value="100KB"/>

      <maxSizeRollBackups value="2"/>

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

        <conversionPattern value="%level %thread %logger - %message%newline"/>

      </layout>

    </appender>

 

    <root>

      <level value="ALL"/>     

      <appender-ref ref="RollingFile"/>

    </root>   

</log4net>

 

Logging to SQL server table

The below configuration will log the exceptions to SqlServer table called Log.

<log4net>

<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">

      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

      <connectionString value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" />

      <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />

      <parameter>

        <parameterName value="@log_date" />

        <dbType value="DateTime" />

        <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />

      </parameter>

      <parameter>

        <parameterName value="@thread" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout" value="%thread" />

      </parameter>

      <parameter>

        <parameterName value="@log_level" />

        <dbType value="String" />

        <size value="50" />

        <layout type="log4net.Layout.PatternLayout" value="%level" />

      </parameter>

      <parameter>

        <parameterName value="@logger" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout" value="%logger" />

      </parameter>

      <parameter>

        <parameterName value="@message" />

        <dbType value="String" />

        <size value="4000" />

        <layout type="log4net.Layout.PatternLayout" value="%message" />

      </parameter>

    </appender>

 

    <root>

      <level value="ALL"/>     

      <appender-ref ref="AdoNetAppender_SqlServer"/>

    </root>   

</log4net>

 

Conclusion

Since developing our own logging framework is time consuming and complex task it will be better if we can reuse an existing tested framework which can save us lot of effort by offering everything we need. In next part of this article, we will see more about log4net framework and customizing it more and more.

Happy coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
title
its so nice
Font Style and Size
Font Style and Size is not good for reading
Web Site Event Trace
Please Update Your Site . Add Web Site Event Trace Document And information For Knowledge ...