Use Log4Net in C# Console Application

In this particular article, we are going to learn on how to use the Log4Net library for creating logs in a Console Application.

Let's begin with creating a Console application in VS2013(you can use any other version you wish) and then install the Log4Net library from the Nuget Package library.

Log4Net

After installing this package, open up AssemblyInfo.cs file under the Properties folder and add the log4net assembly information into it (under the other assembly information.).

  1. [assembly: log4net.Config.XmlConfigurator(Watch=true)]   
Now, open the App.config file and enter required details for LogNet to work.
  1. <configSections>  
  2.     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" /> </configSections>  
  3. <!-- Log4net Logging Setup -->  
  4. <log4net>  
  5.     <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">  
  6.         <file value="C:\\Users\\a0685560\\Downloads\\mylogfile.txt" />  
  7.         <!-- the location where the log file would be created -->  
  8.         <appendToFile value="true" />  
  9.         <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />  
  10.         <layout type="log4net.Layout.PatternLayout">  
  11.             <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout>  
  12.         <filter type="log4net.Filter.LevelRangeFilter">  
  13.             <levelMin value="INFO" />  
  14.             <levelMax value="FATAL" /> </filter>  
  15.     </appender>  
  16.     <root>  
  17.         <level value="DEBUG" />  
  18.         <appender-ref ref="FileAppender" /> </root>  
  19. </log4net>  
Now, that the configuration is complete, let's write the code to create error so that we can log the same.

In our Program.cs file, let's create a function as below:
  1. internal static void Testing()  
  2. {  
  3.     log4net.Config.BasicConfigurator.Configure();  
  4.     log4net.ILog log = log4net.LogManager.GetLogger(typeof (Program));  
  5.     try  
  6.     {  
  7.         string str = String.Empty;  
  8.         string subStr = str.Substring(0, 4); //this line will create error as the string "str" is empty.  
  9.     }  
  10.     catch (Exception ex)  
  11.     {  
  12.         log.Error("Error Message: " + ex.Message.ToString(), ex);  
  13.     }  
  14. }  
Let's just call this function in our main.
  1. static void Main(string[] args)    
  2. {    
  3.     Testing();    
  4.     Console.ReadLine();    
  5. }   
On running the code, we notice a file named "mylogfile.txt" is now created at the location "C:\\Users\\a0685560\\Downloads\\mylogfile.txt".

2016-01-20 15:41:15,558 [8] ERROR TestingLog4Net.Program - Error Message: Index and length must refer to a location within the string.

Parameter name: length
System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
at System.String.Substring(Int32 startIndex, Int32 length)
at TestingLog4Net.Program.Testing() in c:\Users\Vipul\Documents\Visual Studio 2013\Projects\TestingLog4Net\TestingLog4Net\Program.cs:line 34


The log above contains the error message as well as the complete Stack information.

We have many different options for error logging, as mentioned below:
  1. log.Debug();   
  2. log.Warn();   
  3. log.Fatal();   
All these depicts different types of log message.

I would request you to drill into the other methods available in the Log4Net metadata file so as to get more insight into it.

Ebook Download
View all
Learn
View all