HowTo: Logging with Log4Net

imageAs soon as the application works your customer will find the first bugs. In this case it is very important to find out what happened and to find the mistake. Because of this it is helpfully to include a logging while you are debugging.

Log4Net is a very classy library which fulfils you every desire and it takes just a few minutes of work.

 

Log4Net

Log4Net is a quite practical .Net library which is created to make logging easier. There are several different types of “log steps” (debug, error, info,..) and loggings (“Appender”). So for example it´s possible to log into the Visual Studio Debug Window or in a file and so on. It´s also possible to configure it via XML so you are allowed to create log steps on the productivity system.

You can find a good introduction on the homepage of Log4Net.

Practical entrance

To show you the whole problem on a very easy way I´m going to create a consol program and integrate Log4net DLL. Here you will find the “log4net.dll”

 image

 Configuration of Log4Net

The easiest way to configure Log4Net is to use App/Web.Config. Therefore we need to create an “App.config” file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <log4net>
    <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="DebugAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>
</configuration>

Explication:

We define us our own ConfigSections, so it´s possible to control everything central.

In this log4net-section we are going to use the different types of “Appender”. Depending on the Appender there are several ways to log. For example the “ConsoleAppender” logs on the commando line and the “DebugAppender” on the Visual Studio Output Window. Other types of Appender you will find here: Config Examples.

In every Appender it´s possible to guideline the layout so you can adapt the Log Message.

In the last step we chose the level which should be logged – for our example everything, and we are going to use the two appenders.

“Logging Code”

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            ILog logger = LogManager.GetLogger(typeof (Program));

            logger.Debug("Hello World!");
            logger.Error("D´oh!");

            Console.ReadLine();
        }
    }

In Line 5 we dispose Log4Net to check the XML config and than we get our Logger. The Logger has a method for every “Log Level”.

image

Conclusion:

If I´m going to run the application now there is following Output on the console: image

And on the Output Window in Visual Studio:

image

Where exactly should I log?

I didn´t find any general rules but you should keep in mind that the sense of logging is to localise mistakes. So for example you could logout the parameter or “important calls from other services” and the output. With this it´s easier for you to get a feeling for the Code.

Especially with the “DebugAppender” it´s kind of funny if you press a button and you can see how the request walks to the levels and logg out the values. Nerd paradise. J

[ Download Democode ]

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by Code Inside Team

Currently there is no additional info about this author.

One Response

  1. I have writen how to effectively log here: http://morten.lyhr.dk/2010/02/effective-logging.html

    Reply

Comment on this post

Recent Posts

  • Automated Security Analyser for ASP.NET websites

    Evil Hackers are lurking everywhere and many Web-applications are delicately and share “too much” with the attacker. A quick (first!) overview offers the Tool “ASafaWeb”. All the website does is making a few requests and writing an Analyses including problem solving’s. There are no permanent disadvantages (bad requests/ DoS attacks and so on). Example: KnowYourStack.com ...

  • image1489-570x194.png
    „Sign in with Twitter“ for your own ASP.NET WebApp

      “Sign in with Twitter” is a popular practice to authenticate the users on your website. One advantage compared to an own registration is the lower inhibition for the user. But on the other hand Twitter doesn’t fess up with all the information’s and you will get into a kind of addiction. At the end ...

  • image1485-570x194_thumb.png
    CodePlex is going to be updated

      CodePlex the Microsoft Open Source Project Hosting Plattform hasn’t changed that much in the last few years and for a few times I thought Microsoft stopped the whole developing process. But now I found out that there is still life in the project. Maybe it is because of the success of GitHub or because ...

  • image1474_thumb.png
    What does Adobe in the flash-free web? Magazine-Style Layouts with CSS Regions!

      Adobe is well known for Photoshop and Flash but of course there is a lot more. According to the “Future Post” from Google Adobe declared one of their big subjects on a Blogpost. I’m talking about the W3C Working Draft to CSS Regions. Adobe cooperates with the WebKit Team and W3C on this. What ...

  • image1471-523x194.png
    HTML 5 Games, Tooling & 3D

      Game Developing is an interesting subject for all kind of software developer. But as a web developer without any Flash-skills there aren’t that much starting points. With HTML5 and the combination between Javascript, CSS3 and fast browsers there are the first “robust” HTML5 games. HTML5 games? Is this real? Neowin created a “Top 10” ...

Support us