.NET Logging Framework


Introduction There are various logging solutions available for .NET based applications. All these logging frameworks have certain advantages and disadvantages but all of them aim towards helping the user in identifying and solving issues with the applications when it is almost impossible to take help of other debugging and monitoring tools. This article tries to give you an overview of logging in general with a focus on log4net as one of the most commonly used logging framework for .NET applications.

Logging In General An Overview I am almost surprised how at times something as basic and core as a logging framework is ignored during the development & construction phases. As the development team steps into subsequent phases that involve debugging issues on a non personal environment, come the realization for a need to have a solid logging framework. Almost every large application includes its own logging or tracing API irrespective of the underlying technology. Inserting log statements into code is a low-tech method for debugging. It may also be the only way because debuggers are not always available or applicable. This is usually the case for multithreaded applications and distributed applications. Any team can use an effective logging system to diagnose and fix configuration issues. Personally logging has been an important component of any of my development - it offers several advantages. It provides precise context about the execution of the application. Once inserted into the code, the generation of logging output is seamless and effortless. Moreover, log output can be saved in persistent medium (file, event, DB, console etc) for future analysis.

NET Logging Frameworks The following list of .NET logging frameworks forms the most commonly used logging techniques in the .NET world. The selection of one versus the other could be based on the application requirements and architecture as well as an individuals past experience with similar frameworks (no wonder I have always been a supporter of log4net).

Apache Foundation’s log4net Log4net is Apache Foundations .NET equivalent to log4j. one of the first logging frameworks for Java. Log4net is a library-only logging framework which can log basic messages with XML based configurations. It allows multiple logging destinations that can be configured at run time. Log4net is open source and can be downloaded from the project website.

Logging in the Enterprise Library - .NET logging library released by Microsoft as an application block for its Enterprise Library. Besides the typical logging destinations like log files, this logging framework offers the functionality to log to a database or send log files via email. This library is free and can be downloaded from Microsoft’s website.

NLOG Logging Library NLog is another open source logging library for .NET. It is similar to log4net and can be downloaded on its project website for free.

.NET Logging Framework The .NET Logging Framework from The Object Guy is yet another open source logging framework for .NET. It is similar to log4net and NLog and supports different logging destinations.

Apache Log4Net-How Does It Work Apache has provided multiple open source products from web & application servers to logging frameworks all of us at some point would have used one or the other and that makes it difficult to ignore the log4net logger when you are out there looking for one. You can easily find active developer forums/mailing lists for any of their products and that has always made life easier for me while diagnosing some critical issues. Having said that, all the logging frameworks work basically the same: you as an application developer include one of the libraries into your programs and add logging statements to your code. If you start your application and logging is enabled, logging information is sent to the configured logging destination like a log file or monitoring application or event logs. The components of any .NET based application can use Log4Net Logging. It comes with a descriptive SDK documentation that contains samples in both C# and vb.net. Some of the benefits of using the log4net logging framework are:

  • Provides implicit support to track the context of the class you are logging in (refer to the example later in the blog).
  • Allows a configurable and easy way to add multiple appenders - anything from files, events, consoles, databases, etc.
  • Implicit support for tracking context in multithreaded applications
  • Enhanced performance as compared to some of the other competitors

Log4Net Components Log4net has three main components that work together to enable logging:

  • LOGGERS
  • APPENDERS
  • LAYOUT

The biggest advantage of using a logging API over plan System.Console.WriteLine is in the ability to enable-disable certain types of log statements at run time by managing log configurations. This can be done by using loggers that creates a controlled space within the applicant for a specific log type. This space can be categorized by the developer based on the needs. Loggers are retrieved using the static method from the log4net.LogManager class. The GetLogger() methods take the name of the desired logger as a parameter. It takes a Type parameter, uses the fully qualified type name as the name of the logger to retrieve and returns an ILog interface. That is the representation of the Logger passed back to the developer.Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing priority:
ALL DEBUG INFO WARN ERROR FATAL OFF

APPENDERS

. Log4net allows logging requests to print to multiple destinations and such a destination is called an appender. Appenders must implement the log4net.Appenders.IAppender interface. Some of the available appenders are:

log4net.Appender.FileAppender - Writes logging events to a file in the file system.
log4net.Appender.ConsoleAppender - Writes logging events to the application’s Console. The events may go to either the standard our stream or the standard error stream.
log4net.Appender.EventLogAppender - Writes logging events to the Windows Event Log.Each enabled logging request for a given logger will be forwarded to all the appenders in that logger as well as the appenders higher in the hierarchy.
Filters Appenders can filter the events that are delivered to them. The filters can be specified in the configuration to allow fine control of the events that are logged through different appenders. The simplest form of control is to specify a Threshold on the appender. This works by logging only the events that have a level that is greater than or equal to the threshold.

Layouts This is really useful when you want to customize the logging output in a format that you are comfortable with. You can associate a layout with an appender - the layout is responsible for formatting the logging request according to your wishes and the appender takes care of sending the formatted output to its destination.

Configuration Even though the log4net environment is fully configurable programmatically, I have always preferred to configure it using configuration files written in XML. You can add your log4net configuration settings to your project’s app.config or web.config file, it is preferable to use a separate configuration file for better maintainability as well as for placing a FileSystemWatcher object that monitors when it changed so that it can update its settings dynamically. To use a separate config file, add a file named Log4Net.config to your project and add the following attribute to your AssemblyInfo.cs file:[assembly: log4net.Config.XmlConfigurator(ConfigFile = “Log4Net.config”, Watch = true)] Here is an sample log4net config file with several appenders defined:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<log4net><appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"></appender></log4net><file value="..LogsCurrentLog/"></file>
<appendtofile value="true"></appendtofile>
<rollingstyle value="Size/"></rollingstyle>
<maxsizerollbackups value="10?"><maximumfilesize value="10000?"><staticlogfilename value="true/"></staticlogfilename></maximumfilesize></maxsizerollbackups>
<!--Alternatively, roll on date-->
<!--<rollingStyle value=Date/-->
<!--<datePattern value=yyyyMMdd /-->
<filter type="log4net.Filter.LevelRangeFilter"></filter>
<acceptonmatch value="true"></acceptonmatch>
<levelmin value="INFO"></levelmin>
<levelmax value="FATAL"></levelmax>
<layout type="log4net.Layout.PatternLayout"></layout>
<conversionpattern value="%-5level"></conversionpattern>
<!--Specify the level for specific categories (namespace.class)-->
<logger name="ConsoleApp.LoggingExample"></logger>
<level value="ERROR/"></level>
<appender ref="EventLogAppender"></appender>

Implementation Details Here are the different steps or components that need to be configured in order to start using Log4Net framework: Log4Net Binary

  • Download and add Log4Net DLL in the bin folder of the project/website.
  • Add the reference to the log4net.dll in order to use its classes and APIs.
  • Configure Log4Net-log4net.config file To use a separate configuration file as suggested earlier, add a file named Log4Net.config to your project and add the following attribute to your AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = “Log4Net.config”, Watch = true)]

Adding Watch=true allows configuration changes to be made and reflected at run time without requiring a restart of IIS. You need to give the ASPNET user write permission to this directory, which is why it is generally a good idea to leave it out of the web root.

Using a Custom Logger
We can create a custom Logger class which works like a Facade and encapsulates all the implementation for using the Log4Net APIs meant for logging. Call the Logger static public getInstance() method to get a handle to the logger. The getInstance() method requires the calling class type as a parameter since we need to create a separate logger for each class this is helpful in general while going through the log files and being able to easily determine the log statements generated by specific classes.

Create a private static CustomLogger reference in each class that needs to use the logger:

[-]View Code C-SHARP
1
Private static CustomLogger logger = CustomLogger.getInstance(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Once the class has the logger reference, it can start logging by a single line statement:l

[-]View Code C-SHARP
1
logger.logDebug(method name enter your message here);

How to start Logging Pre-Requisites

  • The environment (local or external) should already have the log4net.dll added in the bin.
  • The dll should also be loaded into the memory during startup.
  • Code for a class that needs to use the logger
  • Import project - this project contains the CustomLogger class.
    Make sure the class belongs to a namespace this is important because the logger configuration in log4net.config identifies and finds a class by using <namespace:class> path.Â
[-]View Code C-SHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public partial class LogTestPage : System.Web.UI.Page
{
   // single instance of CustomLogger
   private static CustomLogger logger = CustomLogger.getInstance    (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  //Start Logging
  protected void Page_Load(object sender,EventArgs e)
  {
    try
       {
         //this is specifically for performance logging
         DateTime startTime = DateTime.Now;
         logger.logPerfStart("Page_Load", startTime.ToString());
         logger.logDebug("Page_Load",Entering the method);
         logger.logDebug("Page_Load",Exiting the method);
         logger.logPerfEnd("Page_Load",DateTime.Now.Subtract(startTime).TotalSeconds.ToString());
      }
     catch(Exception e)
     {
        logger.logError("Page_Load",e.Message.ToString());
     }
  }
}

Its time to go and check the logs now
Closing Note - If you are interested in logging and improving the quality of your software and monitoring the application performance and behavior and having a useful tool to support your customer, integrate the log4net logging framework with your .NET application.

0 Response to “.NET Logging Framework”


Leave a Reply