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 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”


 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" ?>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      <level value="All" />
      <appender-ref ref="DebugAppender" />
      <appender-ref ref="ConsoleAppender" />


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)
            ILog logger = LogManager.GetLogger(typeof (Program));

            logger.Debug("Hello World!");


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”.



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:


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 ]

Read more

HowTo: Time-controlled & recurrent functions in .NET & ASP.NET

During a project we had the order to run a specific SQL request after several minutes or seconds and to evaluate them in order to the results. You can solve this problem a little bit “dirty” by using a while(true) loop and Thread.Sleep, or you use a timer. Example: For example we are going to […]

Read more

HowTo: Facebook Connect & ASP.NET MVC

Facebook has created a nice little service named "Facebook Connect". With this application Facebook user are allowed to login into your site with their usual facebook log-in information´s and the whole thing is secured by Facebook. In Fact it´s quite similar to OpenID but it had some more specials than just identification. But in this […]

Read more

HowTo: Cross Domain Ajax with JSONP and ASP.NET

Actually it isn´t possible to send Ajax Requests to addresses which are reachable at the same domain like the site where the script is executed.The reason for this is the Same Origin Policy in JavaScript. There it is given, that the port, the protocol and the domain have to be equal to start requests. This […]

Read more

HowTo: Introduction in to MetaWebLog API

This Blogspot is based on Scott Hanselmans “WeeklySourceCode”, where MetaWebLog API was the subject of today. In the Blogspot he relates that MS use the Windows Live Writer also to administrate their own websites. The tool is absolutely practical and it works with MetaWebLog API. With this tool it´s possible to create “CMS” Content with […]

Read more

Windows 7 RC Training Kit for Developer

Microsoft released the Training Kit for developer yesterday. It contains presentations, Hands on Labs and democode for the new Windows 7 APIs. The Traing Kit is directed towards to C++ developers, but Microsoft offers Wrapper classen for .NET. Topics: Taskbar Libraries Multi Touch Sensors and Location Ribbon Trigger Start Services, Instrumentation and ETW Application Compatability […]

Read more

Visual Studio 2010 & .NET Framework 4 Training Kit – May Preview

Microsoft released a preview Training Kit for .NET 4.0 & VS 2010: Download. It includes 28 presentations, 13 demos & 16 Hands-on Labs.   Overview The Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio […]

Read more

Inside Microsoft’s home of the future

Microsoft shows in a Video how the “home of the future” might look like. Some photos of this house could be found here. Speak recognition & “NUI“s are “key features” in this house.  

Read more

Free eBook: Practical .NET Unit Testing

Nice intro to unit testing (& mocking) with .NET: – Practical .NET Unit Testing

Read more

Free eBook: Testing Chapter from Beginning ASP.NET MVC

Just found an interesting eBook: – Free Chapter of Beginning ASP.NET MVC 1.0 – Testing ASP.NET MVC Applications (Blogpost)

Read more

Recent Posts

  • Time-controlled Azure WebJobs – Azure as easy as it get‘s

        While still in development the Azure WebJob SDK offers some cool features for procession and supply of information. A good example is the sample that observes the Azure Queue and processes an item as soon as it spots one.   Scenario: time-controlled activities – without queue and so on My scenario was quite […]

  • image2021-570x194_thumb.png
    HowTo: Create RSS Feeds with ASP.NET MVC

    I’ve already written about how to consume RSS or Atom Feeds with the SyndicationFeed (in German, sry) but todays post is about how to create or publish an own feed. Beside the age of the feed standard and the much defamation from Facebook, Twitter and Google on RSS/Atom I consider this easy to consume API […]

  • image1997-311x194_thumb.png
    How to access an Azure Website with the local IIS Manager

    Since the end of February it is possible to access an Azure Website with the IIS Manager. Although the Azure Management site offers some information there are more details visible at the IIS Manager. For the connection you will need an IIS Manager and the IIS Manager for Remote Administration Extension. It’s also possible to […]

  • image1929-570x143_thumb.png
    Create and validate own Json-Web-Tokens (JWTs)

    If you are interested in web authentication you probably have heard about JSON Web tokens (JWT). What is a JWT? Maybe I’m not using the correct security termination but however: JWTs are used to exchange claims between two systems. For example: You want to log on to a service (like Facebook, Twitter, etc.) and want […]

  • Micro-Optimization: how to shrink or „embed“ pictures

      I’m currently working on the “CodeInside Dashboard” and since the page structure isn’t that difficult it should be possible to fulfill all of Google Pagespeed or Yahoos YSlow recommendations. One of the rules was to optimize the 4 PNGs that are embedded on the page.   Before – without optimization: Below you can see […]

Support us