Monday, October 27, 2014

Log4net quick learning

log4net


The greatest logging tools out there for .NET is log4net. It’s a tool to help the programmer output log statements to a variety of output targets. There are a three parts to log4net. 
          Configuration -
          Setup
          Call


Logging Levels


1.         OFF - nothing gets logged (cannot be called)
2.         FATAL
3.         ERROR
4.         WARN
5.         INFO
6.         DEBUG
7.         ALL - everything gets logged (cannot be called)

These levels will be used multiple times, both in your code as well as in the config file. There are no set rules on what these levels represent (except the first and last).


Configuration


Configuration is doing in the app.config or web.config file.  There are a few pieces of information that need to be placed in the config file in order to make it work properly with log4net. These sections will tell log4net how to configure itself. The settings can be changed without re-compiling the application.
Root
You need to have one root section to house your top-level logger references. These are the loggers that inherit information from your base logger (root). The root section is the minimum level to log. 

<root>
      <level value="INFO"/>
      <appender-ref ref="RollingFileAppender"/>
    </root>


Additional Loggers


An additional logger that placed in config file to log to the console messages that occur inside the OtherClass class object:

<logger name="Log4NetTest.OtherClass">
      <level value="DEBUG"/>
      <appender-ref ref="ConsoleAppender"/>
    </logger>


ConfigSections


This section is to identify where the log4net configuration is housed.

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>


Appender (General)


It specifies where the information will be logged, how it will be logged, and under what circumstances the information will be logged. 

<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">

The Code


Once you have a reference to the log4net DLL in your application, there are three lines of code that you need to know about
1.         One-time entry that needs to be placed outside of your class. I usually put it right below my using statements in the Program.cs file.  Or 
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
2.         It does a System.Reflection call to get the current class information. This is useful because it allows us to use this code all over but have the specific information passed into it in each class. 
3.         The actual call to log some piece of information.

log.Debug("Application started"); or  log.Info("Info error logging", ex);  …etc.

Download DLL , add reference to your Project and have a try !!!

1 comment: