How to use log4net in C# Console Application

Kailash Chandra Behera | Saturday, July 11, 2020

Introduction

This blog provides complete guidelines use of log4net for How to use log4net in C# Console Application with code example.

Getting Started

The log4net is the most common and popular used logging framework in Microsoft projects. To make your application smooth and faster you need to diagnose your application, log4net provides an environment to track your application activities and record logs or activities in different sources like a file or database.

Demonstration

  1. Open Mircosoft Visual Studio, go to File menu and click on new project. The New Project Winow will appear, then select the Console App(.Net Framework) Temlate.

  2. Give name to project and the path where you want to store, then click on Create button

  3. Install the log4net library by using Manage NuGet Package...

    1. Go to Solution Explorer, then right click on the project name->open Manage NuGet Package for Solution by clicking on the Manage NuGet Package...

    2. Click on the Brose tab, then search for log4net. Install the latest version.

  4. Or you can install it, by Manage NuGet Console with the below command. It will automatically install the latest version

    1. Find the tool menu and expand it.
    2. Expand the NuGet Package Manager.
    3. Click on the Package Manager Console
    4. The Package Manager Console will open, use the below command to download and install the latest version of log4net
     Install-Package log4net  
    
  5. Go to Solution Explorer, then expand the Properties. You will find it just below your project name.

  6. Double click on the AssemblyInfo.cs to open it and paste the below code just after the AssemblyCulture code.

     [assembly: log4net.Config.XmlConfigurator]  
    
  7. Your code placement should look like below code.

     [assembly: AssemblyCulture("")]  
     [assembly: log4net.Config.XmlConfigurator]  
    
  8. Open the App.config file of your project, if you don't have added the App.config file in your project, then follow the below points.

    1. Right click on the Solution Explorer.
    2. Go to Add then click on the New Item..
    3. The Add New Item window will appear, find and select the Application Configuration File then click on Add button.
    4. The config file will be added into your project, open the config file by right clicking on it.
  9. Find the <configSections></configSections> tag, if you don't find added the <configSections> tag, then copy the below code and past it just after the </configuration> tag.

      <configSections>  
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />  
      </configSections>  
    
  10. If the config Sections tag already there, then copy the below code and paste it just after the <configSections> tag.

    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
    
  11. Find the </configuration> tag and paste below code just before the </configuration> tag. This is the log level and appender setting in config for log4net, The code should place between <configuration> and </configuration> tag.

     <log4net>   
       <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">   
          <layout type="log4net.Layout.PatternLayout">   
       <conversionPattern value="%date{ABSOLUTE} [%thread] %level %logger - %message%newline"/>   
      </layout>   
      <filter type="log4net.Filter.StringMatchFilter">   
          <stringToMatch value="test" />   
      </filter>   
      <filter type="log4net.Filter.DenyAllFilter" />   
      </appender>    
       <root>   
       <level value="All" />   
       <!-- If the following line is not included the log file will not be created even if log4net is configured with this file. -->   
          <appender-ref ref="ConsoleAppender" />   
          </root>   
     </log4net>   
    
  12. Note that here in the log4net config, I have used the ConsoleAppender. to use any other appender or more details regarding appenders, visit to my previous blog.

  13. Open the class, where you want implement logging. Copy the below code and paste it just above the controcture of class or where in the place where we declare the property of class.

      private static log4net.ILog Log=log4net.LogManager.GetLogger(typeof(Program));  
    
  14. Invoke the methods of logger class to log messages for your project. For example, to write the exception messages invoke the Error function in the catch block.

  15. Now you are done with the implementation of logging, build your project. see the below code for more..

 class Program  
   {  
     private static log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Program));  
     static void Main(string[] args)  
     {  
       Log.Info("Main method execution started");  
       try  
       {  
         Log.Info("Hello World!");  
         Log.Info("try block executed");  
       }  
       catch (Exception ex)  
       {  
         Log.Error(ex);  
       }  
       finally  
       {  
         Log.Info("Finally block executed");  
       }  
       Log.Info("Test method execution completed");  
     }  
   }  

Summary

Here in the above of this blog, we discussed the each steps on How to use log4net in C# Console Application. I hope you have enjoued it a lot.

Thanks