Friday 2 June 2017

Using Log4Net in Windows Applications

Log4net is an open source library that allows .NET applications to log output to a variety of sources. The log4net library can be downloaded from the project homepage.
Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers provide 5 levels of logging:
1. Debug
2. Information
3. Warnings
4. Error
5. Fatal
The extent of logging done by each level mentioned in above list decreases on going down the list.

Using Log4Net in application

1. Get the DLL :
The log4net library can be downloaded from the project homepage and can be added as a reference in the project used for logging in the .net solution.
2. Configuration [Configuration can be done directly in app.config or separate .config file can also be created]
    a. Configure directly in app.config
   1: <configSections>
   2:     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
   3:   </configSections>
   4:  
   5: <log4net debug="true">
   6:     <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
   7:       <file type="log4net.Util.PatternString" value="${TMP}\MyProject\Logs\Log_%env{USERNAME}_%date{yyyyMMdd}.log" />
   8:       <appendToFile value="true" />
   9:       <bufferSize value="20" />
  10:       <LockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
  11:       <layout type="log4net.Layout.PatternLayout">
  12:         <header type="log4net.Util.PatternString" value="[Log Starts]%newline" />
  13:         <footer type="log4net.Util.PatternString" value="[Log Ends]%newline%newline" />        
  14:         <conversionPattern value="%date [%username] - %message%newline" />
  15:       </layout>
  16:     </appender>
  17:  
  18:     <!-- Specify the level for some specific categories -->
  19:     <logger name="MyApplicationDebugLog">
  20:       <level value="DEBUG" />
  21:       <appender-ref ref="LogFileAppender" />
  22:     </logger>
  23:   </log4net>
    b. Using separate .config file [myLog4net.config]
   1: <?xml version="1.0" encoding="utf-8" ?>
   2: <log4net debug="true">
   3:   <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
   4:     <file type="log4net.Util.PatternString" value="${TMP}\SRG\Logs\Log_%env{USERNAME}_%date{yyyyMMdd}.log" />
   5:     <appendToFile value="true" />
   6:     <bufferSize value="20" />
   7:     <LockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
   8:     <layout type="log4net.Layout.PatternLayout">
   9:       <header type="log4net.Util.PatternString" value="%newline[Log Starts]" />
  10:       <footer type="log4net.Util.PatternString" value="%newline[Log Ends]" />
  11:       <conversionPattern value="%newline%date [%username] - %message" />
  12:     </layout>
  13:   </appender>
  14:  
  15:   <!-- Specify the level for some specific categories -->
  16:   <logger name="MySRGApplicationDebugLog">    
  17:     <level value="DEBUG" />
  18:     <appender-ref ref="LogFileAppender" />
  19:   </logger>
  20: </log4net>
3. Configure the Logger in code
   1: public class LogHelper
   2: {
   3:     private static readonly ILog _debugLogger;
   4:     private static ILog GetLogger(string logName)
   5:     {
   6:         ILog log = LogManager.GetLogger(logName);
   7:         return log;
   8:     }
   9:  
  10:     static LogHelper()
  11:     {
  12:         //logger names are mentioned in <log4net> section of config file
  13:         _debugLogger = GetLogger("MyApplicationDebugLog");
  14:     }
  15:  
  16:     /// <summary>
  17:     /// This method will write log in Log_USERNAME_date{yyyyMMdd}.log file
  18:     /// </summary>
  19:     /// <param name="message"></param>
  20:     public static void WriteDebugLog(string message)
  21:     {
  22:         _debugLogger.DebugFormat(message);
  23:     }
  24: }
4. AssemblyInfo.cs file changes [This file can be find in Properties of the project where LogHelper class is created in Step 3]
a. //if app.config is used, add below line in file
[assembly: XmlConfigurator(Watch = true)]
Or
b. //if separate myLog4net.config is used, add below line in file
[assembly: XmlConfigurator (ConfigFile = "myLog4net.config", Watch = true)]
5. Use it in code
LogHelper.WriteDebugLog(message);
6. Output
Logs will be created at C:\Documents and Settings\<userid>\Local Settings\Temp\<ProjectName>\Logs as mentioned in file tag in configuration file with name as Log_<userid>_date.log
Log file will look like below:-
   1: [Log Starts]
   2: 2012-11-20 18:10:16,668 [domain\userid] - Application started
   3: 2012-11-20 18:12:23,121 [domain\userid] – Calling Load Module Method
   4: 2012-11-20 18:13:09,433 [domain\userid] - Application stopped
   5: [Log Ends]
Issues which might generally come
1. Header and footer coming more times than expected.
Putting XmlConfigurator.Configure() at more than one places may result in having more than one header and footer pair. XmlConfigurator.Configure() should be defined only at one place in the solution. Better approach is to put it in AssemblyInfo.cs as done in example above.
You don’t need below line in LogHelper Class
XmlConfigurator.Configure();
If you have below line in AssemblyInfo.cs class.
[assembly: XmlConfigurator(Watch = true)]
2. Log4net not logging when running application using .exe file instead of visual studio
To avoid this problem move the XMConfigurator configure code from LogHelper class to AssemblyInfo.cs file as done in above example
Summary:
Log4net is a simple and efficient mechanism to do logging in application. By considering above Issues, one can handle unwanted errors in logging which might get noticed during testing.

No comments:

Post a Comment