Close

Note to Self – Using Log4Net in five Simple Steps.

I don’t know about you folks but my memory is quite lousy. At
the ripe age of 26, it’s not as good as its use to be and hence I usually end
up looking things up like when trying to use Log4NET. My favorite destination
is either the Apache website or Nauman’s
article on
Log4NET
. So here is a simple five step process of adding logging to an
application. For times when MS logging app block seems like overkill and
console writing to a text file is not an option, Log4NET is the way to go.

So without further ado

Step 1. Add the following at the top of the application
config file. This tells the config engine that there is a Log4NET section

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <
section
name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
 
</
configSections>

 
Step
2. Add the following before/after appsettings.

<log4net>

    <appender
name="MyApplicationLogFileAppender" type="log4net.Appender.RollingFileAppender">
     
<
param
name="File" value="log\\MyLogFile"/>
     
<
param
name="DatePattern" value=".yyyy-MM-dd-tt&quot;.log&quot;"/>
     
<
param
name="AppendToFile" value="true"/>
     
<
param
name="RollingStyle" value="Date"/>
     
<
param
name="StaticLogFileName" value="false"/>
     
<
layout
type="log4net.Layout.PatternLayout">
       
<
param
name="ConversionPattern" value="%r %d [%t] %-5p %c -
%m%n
"/>
     
</
layout>
    </
appender>
    <
root>
      <
level
value="DEBUG"/>
     
<
appender-ref
ref="MyApplicationLogFileAppender"/>
   
</
root>
  </
log4net>

 

Step 3. Add the following in the AssemblyInfo.cs

[assembly: log4net.Config.DOMConfigurator(Watch
= true)]

 Step 4. Add the following at the top of your class

public static
ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 5. Add the following line in the code where you want
logging to be done.

log.Info("Program Started "
+ DateTime.Now.ToString ());


This will log the info in the MyLogFile in the log folder.

The above steps provide a cookie cutter recipe for jump
start using Log4NET. For further information about what the above config
sections actually mean, please see the following reference articles below.

References

Apache log4net: Home

ONDotnet.com
-- Using log4net

 


Share

2 thoughts on “Note to Self – Using Log4Net in five Simple Steps.

  1. You can easily avoid the performance hit of reflection when initializing a logger by doing it this way:

    public static ILog log = LogManager.GetLogger(typeof(MyClass));

    If you have a large number of classes (and therefore loggers) it could make a noticeable difference to your application startup time, especially if you're using NGen.

Comments are closed.