Wednesday, January 23, 2008

Using Log4net in a Winforms Application

I was trying to use log4 net in my Winforms application and could not get it to work that easily. Here are the steps i performed to get it to works.

1. Offcourse first add the log4net dll to your application as a reference.
2. Then initiate logging as following:

public ILog log;
public void InitiateLogging()
{
log4net.Config.XmlConfigurator.Configure();
this.log = LogManager.GetLogger("user");
}

3. Do not forget to make a log4 net section in your application config file. Here is my config file (my application is named IMSBEWFM. The config file is named: ImsBeWfm.EXE.config

< ?xml version="1.0" encoding="utf-8" ?>
< configuration>
< configSections>
< section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
< /configSections >
< appSettings file="" >
< clear />
< add key="log4net.Internal.Debug" value="true"/>
< /appSettings>
< log4net>
< appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
< file value="general.txt"/>
< appendToFile value="true"/>
< maximumFileSize value="100KB"/>
< rollingStyle value="Size"/>
< layout type="log4net.Layout.PatternLayout">
< conversionPattern value="%d{HH:mm:ss} [%t] %-5p %c - %m%n"/>
< /layout>
< /appender>
< root>
< level value="DEBUG"/>
< appender-ref ref="GeneralLog"/>
< /root>
< logger name="NHibernate" additivity="false">
< level value="DEBUG"/>
< appender-ref ref="GeneralLog"/>
< /logger>
< /log4net>
< /configuration>


4. Notice the:
< add key="log4net.Internal.Debug" value="true"/ >

That line is very usefull in the debug output window of your application log4net will tell you any errors while initializing, tracking down problems. Later when it works you can remove that line.

Now to log someting is quite easy:

log.Debug("Sucessfull login");

Be carefull if you want to log for a released application, then you will have to change level value = "DEBUG" to level value = "INFO" and use log.info in your code to log to the released application.

Excelent reference is: here