Tuesday, July 9, 2013

Step-by-step Setup of log4net with bug fixes for working with VS2010

Step 1: Download log4net
I used log4net for logging in my C# application, however, the log4net version downloaded from the official website at the time has a number of bugs, I have removed those bugs and have it running smoothly with my C# application within the VS2010, the bug-fixed package can be downloaded from:


Step 2: Configure log4net in C# application
To configure log4net, after downloading the bug-fixed version from the above link and unzip it, add the project to your VS2010 solution in the IDE, then double-click your app.config from your VS2010 IDE to open it. Replace its content with the following:

<?xml version="1.0"?>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  <appSettings file="">
    <clear />
    <add key="log4net.Internal.Debug" value="true" />
    <add key="ClientSettingsProvider.ServiceUri" value="" />
      <level value="DEBUG" />
      <appender-ref ref="LogFileAppender" />
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="log-file.txt" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />

The above configuration works with .net 4.0 and log the errors and events to the file named log-file.txt. Next open the Program.cs and add the following line as the first in the Main() method:


Step 3: Use log4net to do the logging
Now open one of your class (e.g. let's say the class name is Animal and has a method called Bark()), add the following line to where you declare your member variables:

private static ILog log = LogManager.GetLogger(typeof(Animal));

Now in the method Animal.Bark(), add the following line to log event:

log.Log("some message");

or the following line to log error:

log.Error("some error");

No comments:

Post a Comment