Sunday, August 31, 2014

How to use log4net in SharePoint based Applications

How to use log4net in SharePoint based Applications


In my current project the requirement is to use log4net as the main logging mechanism to log the errors and exceptions generating from SharePoint based applications. Before this we have used log4net in many .Net based applications and that is pretty much simple to configure and to use. Unfortunately when we implemented log4net the same way in our SharePoint based projects, it failed miserably. So, we started googling and found this is a known issue but we are unable to find out a proper step by step solution to resolve the issue. Fortunately we find out some interesting facts and mechanism to overcome this issue in Mike Knowles bloghttp://mikeknowles.com/blog/2009/02/17/ConfiguringLog4netForSharePointWindowsAuthentication.aspx. So, we thought to collect all the information’s in a single place and to share with you guys. So, let’s start:

Step I

Create your own web app -> Site Collection -> Site.

Step II

Deploy the log4net DLL to the GAC.

Step III

Open your Site’s Web.Config file from Inetpub -> wwwroot -> wss -> virtual directories -> port-no -> web.config
Now, add an entry to the Web.config configSections to register the new configuration block:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />

Next, create a folder named ‘App_Data’ inside ‘Inetpub -> wwwroot -> wss -> virtual directories -> port-no’ folder. Inside App_Data create another folder named ‘Logs’ and inside ‘Logs’, create a text file named ‘RollingFileLog.txt’. Give full Control permission to these 3 file/ folders.
Now add the log4net configuration section to Web.config just prior to the system.web section.
<log4net debug="true">
    <appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
      <file value="App_Data\\Logs\\RollingFileLog.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value="yyyyMMdd" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{dd MMM yyyy HH:mm:ss} [%p] %c - %m%n" />
      </layout>
      <securityContext type="log4net.Util.WindowsSecurityContext">
        <credentials value="Process" />
      </securityContext>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="GeneralLog" />
    </root>
  </log4net>

Now add log4net assembly information in the ‘SafeControl’ section:
<SafeControl Assembly="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" Namespace="log4net" TypeName="*" Safe="True" />

Step IV


Now open your Visual Studio solution. Right Click on the Solution Node and add a new project of type Class Library. Give it a proper name like ‘log4netModule’ as we are actually in a process of creating one HTTP Module. Add reference to log4net dll. Add a strong key into the project.
Add a class file or use the default one. Place the following code inside that file:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using log4net;
using log4net.Config;
using log4net.Util;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace XXX.log4netModule
{
    public class Initlog4netModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            XmlConfigurator.Configure();
        }

        public void Dispose()
        {            
        }        
    }
}

Compile it and copy the error free assembly from the source location.

Step V


Place assembly copied in the last step, inside the ‘bin’ folder present inside the ‘Inetpub -> wwwroot -> wss -> virtual directories -> port-no’ folder. And deploy the same copied assembly into the GAC.
Now, again we need to update the web.config file. Place the following line inside the ‘<httpModules>’ section present inside the ‘<system.web>’ section and modify it as per the name you have given to your project.
<clear />
<add name="Initlog4netModule" type="AZL.log4netModule.Initlog4netModule, AZL.log4netModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4f97192e309c5502" />

Step VI


Open the IIS7 Administration tool via the Start menu, typing in inetmgr.exe in the start/search box and pressing Enter. In the tool, double-click on your server node in the left-hand treeview, then expand the “Sites” node, and double-click on the site or application to which you would like to add your module and handler.
Select the “Modules” feature icon, then click the “Add Managed Module …” action, and in the resulting dialog box type in the module name (arbitrary) and then select the type in the dropdown box, as the tool will automatically load your assembly in bin and discover types that implement the IHttpModule interface. Press OK to add the module.
clip_image001[4]
Reset IIS.

Step VII


Now, open up your original solution in visual studio. In the desired page add a reference to the log4net assembly.
using log4net;

Next, to test if at all log4net is working or not, place the following lines inside your page load event:


ILog log = LogManager.GetLogger("TestLogger");
log.Debug("Error logged");

Save and compile and run the solution.
If you have followed all the steps perfectly, then the log file present inside the Logs folder should have the following entry:

“<Date Time>  [DEBUG] TestLogger - Error logged”

No comments:

Post a Comment