Martin Suchan – BloQ Random #WPdev stuff

31Jan/111

Logging with log4net in SharePoint

It's actually pretty easy - I spend several hours looking for right answers how to use log4net logging properly in custom WSS feature/web part. I found several guides on Internet mostly containing points as:

  • modify manually your web.config
  • add loading script to your global.asax page
  • add manually log4net library into SafeControls
  • restart IIS app pool after the installment

Actually you don't need anything from this list, it's much simpler...

What you need:

- VS 2008 or VS2010
- WSPBuilder - you probably know this "must-have" tool for deploying custom SharePoint features. I use the latest beta 1.4 which works in VS 2010.
- log4net library, obviously ๐Ÿ™‚

Step 1. The basics: Create new project in VS of type WSPbuilder Project, add into this project New Item of type WSPBuilder -> Blank feature. Paste here code of your SharePoint feature, make sure feature.xml and elements.xml files are properly set. Add reference to your log4net library to your project. Next create folder named GAC in your project and "Add existing item" the log4net.dll into this folder. Dlls in this folder are deployed into GAC during the installment of this feature - this is necessary, but pretty easy task.

Step 2. Setting up log4net: Create config file with settings for log4net - this is the core task - the setting is basically several lines of xml with information like what kind of data to log, where to write, what date and time format to use, etc. Having separate config file for log4net is the great feature of this library - you don't need to recompile your solution to change the amount of information to be logged, just change the config and probably restart your (web) application.

The config file for log4net could be located in several places - it could be hardcoded in source file, but that's not the recommended solution, it could be in a separate file loaded at the start of the application, it could be also located within your web.config or app.config file. I've chosen to put it in a separate folder - it's pretty convenient and you don't need to handle adding it manually into web.config. An example location I used is the folder: "12/CONFIG/log4net.config" This is a global folder located most likely in thi path
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\

In you Project just create the folder 12/CONFIG and create fil;e named log4net.config within.
Step 5. Set and load log4net settings. Add this settings to your log4net.config file

<?xml version="1.0"?>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="Logs\Log4Net.log"/>
<appendToFile value="true"/>
<maximumFileSize value="500KB"/>
<maxSizeRollBackups value="20"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
</layout>
</appender>
<logger name="File">
<level value="All"/>
<appender-ref ref="LogFileAppender"/>
</logger>
</log4net>

This setting adds Appender for logging into Logs/log.txt file. This file is then located in this directory
C:\Inetpub\wwwroot\wss\VirtualDirectories\<port>\Logs

Step 3. Initialize the logger in your application: In my app I created simple wrapper for logging and initialization. When accessing this class for the first time it is initiated with our log4net.config file and is ready for further use.

public static class LogHelper {
private static readonly ILog log;
static LogHelper() {
XmlConfigurator.ConfigureAndWatch(
new FileInfo(SPUtility.GetGenericSetupPath(@"CONFIG\log4net.config")));
log = LogManager.GetLogger("File");
log.Debug("XmlConfigurator now configured");
}
public static void LogError(string message, Exception ex) {
log.Error(message, ex);
}
public static void LogInfo(string message) {
log.Info(message);
}
}

The important line here is the:
XmlConfigurator.ConfigureAndWatch(new FileInfo(SPUtility.GetGenericSetupPath(@"CONFIG\log4net.config")));
which tells the logger to load that file and watch it for changes.

Step 4. Build your solution, use WSPBuilder to build WSP file and deploy it to your web or farm, open your new feature which uses the LogHelper and check, if there is no exception and message is written to the target log file. And that's all, how cool is that? ๐Ÿ™‚

Just a note for the end - you may want to store you log4net.config file in a app-specific location. Currently used location is server-wide and it might be a problem if there is other web application using log4net. Also make sure the log file is accessible and writable by your web application.

Also an important note - if you don't want separate config file for log4net, there is only one other solution how to initiate the logging - using entry in web.config. Note app.config can't be used because we are not creating desktop application, but web application. ย Just don't waste time trying to use app.config - it won't work. Using web.config is possible, but the configuration is more tedious. I wont cover this approach here, just take a look on these sources:

Sources:
Probably the most exhaustive and thorough guide:
http://www.thespgeek.com/2011/01/how-to-use-log4net-in-sharepoint-based.html
Blog post which helped me most:
http://geekswithblogs.net/bsherwin/archive/2008/02/15/119657.aspx

Filed under: .NET Leave a comment