Using Log4Net in a Shared Hosting Environment
26 Sep 2011
.net adonetappender log4net medium trust mvc
Another day and another shared web hosting issue. This time it's with Log4Net and its AdoNetAppender. The AdoNetAppender is used by Log4Net to append logging events to a table within a database. This is my preferred method for logging any live site errors within my web applications. However the latest release of Log4Net (1.2.10) will not allow the use of the AdoNetAppender within a medium trust environment. Fortunately after a lot of trawling through forums and blogs I finally stumbled onto a fix...
To demonstrate the fix let's run through the basic steps for adding Log4Net to a web project with an AdoNetAppender.
Download the latest release of Log4Net (http://logging.apache.org/log4net/download_log4net.cgi) and add a reference to the downloaded Log4Net release dll to your web project.
Add the relevant configuration settings to your web projects Web.config file for Log4Net and include an AdoNetAppender.
Inform the Log4Net library that it should be looking in the Web.config for its configuration settings by adding the following code to your Global.asax.
Finally somewhere in your application code try and log something.
In order to test this set up under shared hosting conditions you should also add the following config setting to your Web.config file to run the web application with medium trust privileges.
Now fire up the web application and you will see the following Log4Net error whenever it tries to log anything via the AdoNetAppender.
Visual Studio Output Window
So you can't use Log4Net with an AdoNetAppender in a shared hosting environment... well actually you can. This problem has actually been fixed in the latest Subversion branch of the Log4Net code but has yet to make it into a release. In order to get the latest branch code use an SVN client, TortoiseSVN (http://tortoisesvn.net), to download the latest code from the Log4Net source repository: http://svn.apache.org/repos/asf/logging/log4net/trunk/
Now replace the referenced Log4Net dll in your web project with the dll produced by building the latest branch code.
Re run your web application and hey presto, no Log4Net error. You should start to see rows appearing in your database log table.
Log Table Select Query