Using log4net from Sharepoint 2007

Using log4net from Sharepoint 2007

I had previously written about using lo4net from Sharepoint
by including all the configuration settings in the code.

This certainly works, and its very easy.

It would be good to be able to use a standard log4net configuration
file though. In fact that would be great.

And you can.

FileInfo configFile = new FileInfo(_LOG4NET_CONFIGURATIONFILE);
XmlConfigurator.Configure(configFile);

It is that simple.

In the code above _LOG4NET_CONFIGURATIONFILE is a configuration setting I read from the Sharepoint configuration file, but you can hardcode it instead.           

You have to make sure that you put the configuration file in a location that Sharepoint can read from .

One such place is

C:\Inetpub\wwwroot\wss\VirtualDirectories\80

I find it tidy to keep the log4net file next to the web.config file as well.

You can also read from the web.config file that Sharepoint uses with this code:

Configuration config = null;
config = WebConfigurationManager.OpenWebConfiguration("/", "Sharepoint - 80");

 

 

 

Phil Haack explains configuring log4net in asp.net 2.0 application. We can keep the configuration in the web.config, and we need to tell the log4net, that where we kept the configuration in the Application_Start() event using XmlConfiguration.Configure() menthod. In asp.net we can add a Global.asax and keep this code in Global.asax.cs.

But how can we do this in Sharepoint?

Every site collection we create in sharepoint, creates a globals.asax file and keeps in the webapp root directory. The asax files contains the following code.

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>

We can add a inline code in the global.asax file as follows,

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Assembly Name="log4net, version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" %>
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>
<%@ Import Namespace="log4net.Config" %>

<script runat="server">
void Application_Start(Object sender, EventArgs e)
{

// Configure log4Net, to take its configuration from the web.config file.
XmlConfigurator.Configure();
}
</script>

or we can derive a class from SPHttpApplication and add the Application_Start() method.

 

你可能感兴趣的:(Using log4net from Sharepoint 2007)