A beginner tutorial – Log4Net

The log4Net is a message logging tool. It is a powerful framework that has been in use since many years and yet it is still preferred. This is used to log messages from the application. In case of developers, this helps in locating the problems in the application. I have tried here to give the fair idea about how one can use log4net framework in their application while developing it. This tutorial is mainly for C# developers and also for test automation engineers who would be using C#.

  1. Create a console project using your visual studio
  2. Open the Solution Explorer
  3. Select and Right click on the project you created. Select “Manage NuGet Packages…” option.
  4. Install log4net from NuGet packages

Click on online > Search for log4net and install. Follow the sequence shown in the image below:

Step 1

Close the NuGet package manager window, once the installation is over.

5. Add the below code in assemblyinfo.cs5. Add the below code in

assemblyinfo.cs [assembly:log4net.Config.XmlConfigurator(Watch=true)]

Step 2

Why is it?

This would let know the log4net to look at application configuration for the configurations setup.

6. Add the following code snippet to Program.cs

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 3

Why is it?

You are building a bridge between the application (who is logging a message, in particular) and the log4net framework. This helps log4net to hear the message who is saying it from the application.

7. Open app.config file and add the following configurations

Now it’s time to set some configurations:

You are declaring custom configurations here. And they go into configSections element

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
          <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
          </configSections>
          <log4net>
                   <root>
                             <level value="ALL" />
                             <appender-ref ref="ConsoleAppender" />
                   </root>  
                   <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
                             <layout type="log4net.Layout.PatternLayout">
                                      <conversionPattern value="%date %5level %logger - %message%newline" />
                             </layout>
                   </appender>
          </log4net>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

NOTE: We will explore little more about these configurations later. For now, we will go ahead to know how we can log a message.

Add the following line of code in program.cs file

log.Info("This is my first logger example");

Finally, your program.cs file should look like this:

Step 4-2

8. Run the application (Ctrl+F5)

You should be getting the log as you are expecting in Program.cs

Step 5-1

The message that you are expecting is printed on a console window.

Now, let’s discuss about the configurations we set in app.config fileLevel

This node in app.config tells your log4net framework to consider what kind of messages from your application has to be logged. There are few different levels and they are:

  • FATAL
  • ERROR
  • WARN
  • INFO
  • DEBUG
  • ALL – All messages
  • OFF – No messages are logged.

If any of these is set in level node, only such messages of category are logged.

For ex: if the level node is set to “FATAL” in app.config, only those messages will be logged. Note that, ALL and OFF levels can’t be called in your code.

In the below screen, I have modified program.cs to have few more messages to be logged.

step 6

Also, the level is set to FATAL in app.config file

step 8

Now run the program.cs again.

As you can see in the above screen that there is only a fatal error message logged. But the info message is not logged.

Apart from this, there are other several appender options available. Most commonly used appender is RollingFileApender.

RollingFileAppender:

This appender creates a log file at the location specified in the config file. The advantage of this appender is, no need to bother about the growing size of the log file. Log4net framework would manage automatically to take backup of log file once it reaches the specified file size in the config settings.

The configurations set in app.config would look like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
       <configSections>
              <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
       </configSections>
       <log4net>
              <root>
                     <level value="ALL" />
                     <appender-ref ref="RollingFileAppender" />
              </root>
              <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
                     <file value="C:\Log4Net\log.txt"></file> <!--This is the location-->                      <appendToFile value="true"/>
                     <rollingStyle value="Size"/>
                     <maxSizeRollBackups value="1"/>    <!--This sets the number of times the backup should be taken-->
                     <maximumFileSize value="5KB"/>     <!--This is the max size of the log file. After this, the log file gets backed up and a new file is created -->
                     <staticLogFileName value="true"/>
                     <layout type="log4net.Layout.PatternLayout">
                           <conversionPattern value="%date %5level %logger - %message%newline" />
                     </layout>
              </appender>
       </log4net>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>

After all the changes made, run again the application. Once the application is run successfully, you should be able to find the log file created in path specified in config file and the messages are logged with in that log file.

step 9

Filters:

These filters are applied to the appenders in log4net configurations. These help in writing the messages only that are needed. These filters are of different type. The one is explained below.

<filter type="log4net.Filter.LevelRangeFilter">
       <levelMin value="DEBUG" />
       <levelMax value="WARN" />
</filter>

As it specifies it is a level range filter. Here, you mention a minimum level and maximum level of message categories.

After filters applied, the following is what logged in log file

step 10

Layouts:

Layouts help users to customize and format their logs in the style they want.

In our sample, we have used something like this:

<layout type="log4net.Layout.PatternLayout">
       <conversionPattern value="%date %5level %logger - %message%newline" />
</layout>

The pattern mentioned above would tell the log4net framework to format and print the message as

“2017-07-10 05:58:13,863  INFO Log4NetLearning.Program - This is INFO message”
date level logger message newline
2017-07-10 05:58:13,863 INFO Log4NetLearning.Program This is INFO message A newline after each message

I hope this write up helped you in understanding little about message logging and the log4net framework. There is still lot more to know about log4net. If you wish to know more, here is log4net user manual.

Advertisements

One thought on “A beginner tutorial – Log4Net

  1. Pingback: Configure Log4Net with ASP.NET MVC – Developers Log

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s