Welcome!

.NET Authors: Bruce Armstrong, Pat Romanski, Liz McMillan, Yeshim Deniz, Dmitry Sotnikov

Related Topics: .NET

.NET: Article

.NET Application Logging Mechanism

Creating a Standard Rule for Coding and Debugging

In application development, one should consider an effective way of creating a standard rule for coding and debugging. For all the information provided in the application code, there's a better way for developers to track down a problem and find a solution.

The logging mechanism is one of the low-tech solutions for serving up information for tracking down application code. In this article I'll try to provide a tutorial for using the Log4Net logging framework adapted from the log4j framework that's currently the most popular logging mechanism for the Java platform.

Log4Net API
The framework supported by the log4net logging API is currently available as shown below:

  • Microsoft .NET Framework 1.0 (1.0.3705)
  • Microsoft .NET Framework 1.1 (1.1.4322)
  • Microsoft .NET Compact Framework 1.0 (1.0.5000)
  • Mono 1.0
  • Microsoft Shared Source CLI 1.0
  • CLI 1.0-compatible
The frameworks don't have all the same features (see http://logging.apache.org).

Logger and Appenders
For developers to be able to apply the logging inside the application code, it's important to understand the three main components in the logging API. Those three components are:

  • Logger is a named entity that's assigned by a named hierarchy that follows hierarchal naming rules.
  • Appender objects are primarily responsible for printing logging messages at different destinations such as consoles, files, sockets, and NT event logs. Occasionally Appender objects can have Filter objects associated with them that make further decisions about logging a particular message.
  • Logger objects that act in a particular instance of an application follow a parent-child hierarchy (see Figure 1).
At the top of the hierarchy is a Root logger. Since a root logger doesn't consist of the namespace, it will be custom for outside the scope.

Typically the child logger will inherit the following properties from the parent logger:

1.  Level
Level define4s the severity or priority of the logger message. Level is a class of the Log4Net.Core package. This class defines the following levels:
- ALL - (Lowest) All possible logging information has been turned on.
- DEBUG - This level means that only logging debug information is available. It is usually very useful during the development stage.
- INFO - This level refers to logging the information stemming from application flow.
- ERROR - This level means logging the error message related to the application error.
- WARN - This level means that a warning message related to the application needs immediate attention because of unexpected behavior.
- FATAL - This level refers to a system-critical problem.
- OFF - (Highest) All logging information has been turned off.

2.  Appender
Appender is the object responsible for storing a message in the repository such as console, plain text file, database, and other repositories. Appender has a filter feature that handles the filtering process of the message logging request to the repository.

Formatting Logging Information
Log4Net provides various layout objects that format the logging data according to various layouts. It means that developers can create an application-specific format of the logging information using different layouts. There are seven types currently available for the layout objects log4net:

  • Log4Net.Layout.ExceptionLayout:
    Layout objects to render exception text from the logging event.
  • Log4Net.Layout.PatternLayout:
    Layout objects to format the logging event according to a flexible set of formatting flags.
  • Log4Net.Layout.RawTimestampLayout:
    Layout objects to extract the timestamp from the logging events.
  • Log4Net.Layout.RawUtcTimestampLayout:
    Layout objects to extract the timestamp from the logging events in universal time.
  • Log4Net.Layout.SimpleLayout:
    Layout objects to format the logging event with a simple format ([level] - [message]).
  • Log4Net.Layout.XmlLayout:
    Layout objects to format the logging event as an XML element.
  • Log4Net.Layout.XmlSchemaLayoutLog4j:
    Layout objects to format the logging event as an XML element that's compatible with log4j event dtd.
Log4Net Configuration
Log4Net can be configured using the application info configuration file, with configuration steps as follow:

1.  First we need to define the log4net configuration handler under the configuration section.

<configSections>
   <section name="log4net" type="log4net.Config.Log4NetConfigura-tionSectionHandler, log4net" />
</configSections>

2.  Define how the logging information message will be processed either in the console or the repository. This definition will use the Appender object mentioned above as the object primarily responsible for printing messages to different repositories.

<appender name="Screen" type="log4net.Appender.ConsoleAppender">
   <layout type="log4net.Layout. PatternLayout">
       <conversionPattern
       value="%-5level [%C]
     %date{dd MMM yyyy
     HH:mm:ss,fff} :
       [%method] :
     %message%newline"/>
   </layout>
</appender>

<appender name="PlainText" type="log4net.Appender.RollingFileAppender">
    <file value="application.log"/>
      <appendToFile value="true"/>
      <maximumFileSize value="200KB"/>
      <maxSizeRollBackups value="10"/>
      <layout type="log4net.Layout. PatternLayout">
        <conversionPattern
        value="%-5level [%C:%L]
      %date{dd MMM yyyy
      HH:mm:ss,fff} :
    [%method] :
    %message%newline"/>
</layout>
</appender>

This configuration example is divided into two types of appenders, the first is the appender responsible for printing the message in the console or screen, and the second appender will be responsible for printing the logging information in a plain text file. The object of the RollingFileAppender features give us flexible log file behavior; based on the configuration above it shows that the file generated for logging is application.log file and that maximumFileSize is the parameter that defines that the maximum size file will be a rolling 200 kilobytes. That means that the application.log will be moved into application.log.1 when the size of file reaches 200 kilobytes and maxSizeRollBackups is the parameter that defines the maximum rolling file. As shown at the configuration above, the layout object as well as the conversionPattern has a format value:

  • %-5level: This format pattern means that the reserved level of the logging information will be five characters.
  • %C: This format pattern is the definition of the logger name.
  • %L: This format pattern defines the line number where the logging request was issued.
  • %date: This format pattern indicates the output date in local time.
  • %method: This format pattern defines the output method.
  • %message: This format pattern is the output message from the logging request.
  • %newline: This format pattern indicates a new line request.
For more information about the conversion pattern see http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html. 3.  Define the root-logging configuration. This configuration will set the level and wiring the appender configuration to be handled by the log4net framework.

<root>
      <level value="ALL"/>
      <appender-ref ref="Screen"/>
      <appender-ref ref="PlainText"/>
</root>

Developing Code with log4net
In this code example we'll try to develop a login module using the .NET Web application that implements the logging request using the log4net API as its logging information.

To enable the log4net mechanism, the first thing we have to do is load the configuration into the application as shown in the code called the global.asax.cs file below:

protected void Application_Start(Object sender, EventArgs e)
{
      XmlConfigurator.Configure(new FileInfo(
      AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) );
}

This code shows us that when the application loaded the XmlConfigurator object from the log4net.Config package, it will configure the configuration we already set under the web.config file.

Before we move on, we need to prepare the UserEntity object, which has two properties: LoginId and Password with a String variable type. Basically LoginId will store the information of user login identity, and the password property will store the password of the user sign-on into the application (see Listing 1).

The next step is to develop a screen for Web application for the user to sign on to the application. The screen will be look like Figure 2.

After designing the login screen we'll move on to the authentication code that implements the logging mechanism inside the module code (see Listing 2).

More Stories By Sonny Hastomo

Sonny Hastomo is an IT architect at Sun Microsystems, Indonesia, for the telecommunication industry division. His currently is focusing on providing solution design, sizing, implementation, consulting services, and quality support to customers in their evaluation of their IT challenges.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
SYS-CON Brazil News Desk 06/28/06 05:06:40 PM EDT

In application development, one should consider an effective way of creating a standard rule for coding and debugging. For all the information provided in the application code, there's a better way for developers to track down a problem and find a solution.