This tutorial is brought to you by NetroStar, a website development company.
One of the most popular logging frameworks for C# nowadays is log4net. In this tutorial I'll show you how to configure it and how it works. This tool is open source and allows you to create various logs in different output targets. It's very similar to log4j - logging tool for Java. We'll configure it to work on the example of web application but it's almost the same to setup it for other Visual Studio projects.
First step is to download log4net from their homepage: http://logging.apache.org/log4net/. Go to the download section and choose the most current version.
Then after creating a new project in Visual Studio we have to add reference to log4net library. To do this go to the Solution Explorer window on right hand side and right-click on the References folder and click Add Reference.

Then in the opened window choose Browse tab, find log4net dll file in the package that you just downloaded and click Add button.
Now we'll configure web.config or app.config file depending on what type of project you're creating. Add to this file following code within <configuration> tag just in the beginning:
Then we'll add local variable that will represent our logger. To do so add following code to you code-behind file:
Now depending on the type of the project you created and the class you have to specify in this code type of your main class. So you have to put name of your class in typeof() method. In my case this name is Global.
Finally we'll have to add following code to the code-behind file that runs on application startup, again the name of this method depends on the type of the project you are working on. In the case of web application it's Application_Start.
Now you can just run your application. This will create a new file: C:\temp\log.txt. There are 5 levels of messages in log4net:
- Debug
- Info
- Warn
- Error
- Fatal
You can add each of these wherever you need it. To see how it works add following code somewhere in your application:
After running such application, your log file should look like this:
INFO 2011-07-16 01:48:50 – log4net is working correctly
DEBUG2011-07-16 01:48:50 – Debug log
INFO 2011-07-16 01:48:50 – Info log
WARN 2011-07-16 01:48:50 – Warn log
ERROR2011-07-16 01:48:50 – Error log
FATAL2011-07-16 01:48:50 – Fatal log
Summing up log4net is very useful tool for logging that you can use with different types of .NET applications.
This tutorial is brought to you by NetroStar, a web design company.