Quick and Dirty Guide to Configuring Log4Net For Web Applications

UPDATE: I wrote a post with notes on getting this to work with ASP.NET 2.0.

Looking around, I noticed a lot of people struggling with getting Log4Net to work with their web applications (ASP.NET 1.1). I’m not going to spend a lot of time digging into Log4Net here, as you can do a Google search for that. But I will give you a quick and dirty guide to quickly getting it set up for a website. Bar of soap not included.

Using a Separate Config File

Although you can put your Log4Net configuration settings within the web.config file, I prefer to use a separate configuration file. Log4Net is a bit of an elitist. It won’t dare put a FileSystemWatcher on web.config nor App.config. However, if you tell it to use its own config file, it will gladly monitor that log file and update its settings on the fly when the file changes.

Specifying the Log4Net Config File

If you use a separate config file, a quick and easy (and dirty) way to have your application find it is to place the config file in the webroot and add the following attribute to your AssemblyInfo.cs file.

[assembly: log4net.Config.XmlConfigurator( 
ConfigFile="Log4Net.config",Watch=true )]

Declaring the Logger

At the top of each class that I plan to use logging in, I declare a logger like so:

private static readonly ILog Log = LogManager.GetLogger( 
MethodBase.GetCurrentMethod().DeclaringType);

The reason I place a logger in each class is to scope it to that class. If you read the log4Net docs, you’ll see what I mean by this.

Using the Logger

Once you’ve declared the logger, you can call one its logging methods. Each method is named for the logging level. For example:

Log.Debug("This is a DEBUG level message.  
Typically your most VERBOSE level.");

Now whether that message shows up in your logs depends on how you’ve configured your appenders and the logging level you’ve set. Don’t understand what that means? Read the Log4Net introduction.

Sample Web Solution

In order to make all this discussion very concrete, I’ve gone ahead and did all your homework for you by creating a simple ASP.NET 1.1 web solution (Log4NetSampleSolution.zip ) using Visual Studio.NET 2003. After unzipping this solution, you should be able to build it and then view the default.aspx web page. This page will log a few very interesting messages of varying levels to three appenders.

Of special note is the use of the RollingFileAppender as seen in this snippet.

<appender name="RollingLogFileAppender"    
        type="log4net.Appender.RollingFileAppender">

    <file value="..\Logs\\CurrentLog" />
    <appendToFile value="true" />
    <datePattern value="yyyyMMdd" />

    <rollingStyle value="Date" />
    <filter type="log4net.Filter.LevelRangeFilter">
        <acceptOnMatch value="true" />

        <levelMin value="INFO" />
        <levelMax value="FATAL" />
    </filter>

    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern 
        value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
    </layout>

</appender>

Note that the file value (with backslashes escaped) points to ..\Logs\CurrentLog. This specifies that Log4Net will log to a file in a directory named Logs parallel to the webroot. You need to give the ASPNET user write permission to this directory, which is why it is generally a good idea to leave it out of the webroot. Not to mention the potential for an IIS misconfiguration that allows the average Joe to snoop through your logs.

[Listening to: Envy / Faith - Deep Dish - Global Underground 021 - Moscow CD2 (4:51)]
[ad] Free Bug Tracking & Project Management Software Axosoft’s OnTime 2007 allows software development teams to collaborate on software projects by tracking everything from defects to enhancements to helpdesk incidents in one easy-to-use database driven by an intuitive Windows, Web or VS.NET Integrated UI. Get a Free Single-User License ($200 Value!)

What others have said

Requesting Gravatar... sam Mar 12, 2005 8:42 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Exactly what I was trying to accomplish. Thanks.
Requesting Gravatar... bags Mar 17, 2005 7:36 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Great info - thanks. This works for a website and the classes (Page) objects in the website. What about when the website uses different class libraries? How do I configure the class libraries so that they, too, will log to the same location as the website code does? Can I have the class libraries point to the log4net config file that is used by the website?

Thanks in advance.
Requesting Gravatar... Haacked Mar 17, 2005 8:07 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
That's the beauty of it. If your classes are declaring a logger, they will log to wherever the executing application is configured to log to.

If you think of your application as an assembly graph, you need to configure your assembly and all the rest pick up that setting.

Typically your root assembly is your website or your EXE.

Hope that helps.
Requesting Gravatar... coolguy Apr 01, 2005 12:17 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Thanks a lot. You don't believe I have been looking for it since 41/2 hours, most of the examples out there: either they are difficult to configure or difficult to understand.
Good work, keep it up
Requesting Gravatar... Haacked Apr 01, 2005 12:51 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Glad it helped! Thanks for the compliment.
Requesting Gravatar... Rohit Apr 09, 2005 4:26 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Hello,

We are evaluating log4net for one of our customers.

Our application consists of Asp.Net application which uses remoting.
We have included log4net in both web application and remoting application.
but the log4net logs the debug info only for the web application and not in=
the remoting application.
It doesn't even creat the log file in the remoting application directory.
we have given necessary permissions for the folders.

Help on the same is much appriciated. Thanks!

Regards,
Rohit

The following is mentioned in web.config of remoting application
<configSections>
<section name=3D"log4net" type=3D"log4net.Config.Log4NetConfigurationSect=
ionHandler,log4net" />
</configSections>

<log4net>
<appender name=3D"FileAppender" type=3D"log4net.Appender.RollingFileAppen=
der">
<param name=3D"File" value=3D"Test.log" />
<param name=3D"AppendToFile" value=3D"true" />
<param name=3D"RollingStyle" value=3D"Date" />
<param name=3D"MaxSizeRollBackups" value=3D"30" />
<param name=3D"DatePattern" value=3D"yyyyMMdd" />
<layout type=3D"log4net.Layout.PatternLayout">
<param name=3D"ConversionPattern" value=3D"%d [%t] %-5p %c [%x] - %m%n"=
/>
</layout>
<filter type=3D"log4net.Filter.LevelRangeFilter">
<levelMin value=3D"DEBUG" />
<levelMax value=3D"WARN" />
</filter>
</appender>
<appender name=3D"EventLogAppender" type=3D"log4net.Appender.EventLogAppe=
nder">
<applicationName value=3D"ApplicationName" />
<layout type=3D"log4net.Layout.PatternLayout">
<conversionPattern value=3D"%date [%thread] %-5level %logger [%ndc] - %=
message%newline" />
</layout>
<filter type=3D"log4net.Filter.LevelRangeFilter">
<levelMin value=3D"ERROR" />
<levelMax value=3D"FATAL" />
</filter>
</appender>
<root>
<level value=3D"DEBUG" />
<appender-ref ref=3D"FileAppender" />
<appender-ref ref=3D"EventLogAppender" />
</root>
</log4net>

Also in the AssemblyInfo file we have added this line
[assembly: log4net.Config.DOMConfigurator(Watch=3Dtrue)]=
Requesting Gravatar... Haacked Apr 09, 2005 10:15 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Rohit, which version of Log4Net are you using. The config sample you sent me uses a different syntax than what I used.
Requesting Gravatar... Rohit Apr 12, 2005 4:24 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Thanks for the reply, we are using .Net framework version 1.1 and log4net version log4net-1.2.0-beta8. Please let me know where we are going wrong.
I also noticed that log.IsDebugEnabled(also any other IsxxxEnabled) function always returns false. I tried with the same configuration with other test projects i created it works but it doesn't work with my actual application. [It doesn't work with the Remoting application but same configuration works with web application]
Thanks again fro the reply...
Requesting Gravatar... Haacked Apr 14, 2005 8:28 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
I'm using version 1.2.0.30714 and the only thing I noticed is that your configuration file was very different from mine in how you declared the appenders.
Requesting Gravatar... AspNet Apr 21, 2005 1:24 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Hi all,

I need help to set the log4net to delete log files automatically after 10days.
Requesting Gravatar... Al May 17, 2005 10:11 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Hi

I'm simply trying to get NUnit to run some tests that log, with the Test project being the one that starts the application logging. In fact, ive seen this before and this is what im trying todo: im using a configuration class (that will utlimately read from the registry or db) that says where the configuration path should be, and that in turn tells to write to file, ill write out the TestFixture first and then the config file. I dont get any errors but neither do i get a file created or written to... thanks for any help!

[TestFixture]
public class TestLogging
{

static TestLogging()
{
string configFile = Configuration.LogConfigFilePath;
log4net.Config.DOMConfigurator.Configure(new System.IO.FileInfo(configFile));
ILog log = LogManager.GetLogger(typeof(TestLogging));
log.Info("Starting Logging");
}

[Test]
public void Test()
{
ILog logger = LogManager.GetLogger("my logger");
logger.Info("Logging the Test() method");
}
}





<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="c:\logs\log-file.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
Requesting Gravatar... Emil May 20, 2005 7:20 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Great, just what I needed. Been pounding my head against the wall for last couple of hours, trying to get it work, and this was excactly what I needed to get starting.

I've made 2 slight chances though

1. I put the assembly line in the global.asax instead of the assembly.cs. As far as I can tell it makes no difference and it just seems a bit more 'logical' place to me - purely a question of taste (and of where I suspect my collegues will be able to find it :)

2. I've used
[assembly: log4net.Config.XmlConfigurator( ConfigFile="Log4Net.config",Watch=true )]

Although it compiled just fine, I got a warning saying that the DOMConfigurator was obsolete and that the XmlConfigurator should be used instead - so I did :)


/emil@obey.your.compiler.or.die.com
Requesting Gravatar... Evan Jun 21, 2006 11:48 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Any idea why my IsXXXXXEnabled properties always return false? Here is my config...

<log4net>
<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<!--connectionTyte value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /-->
<connectionString value="Data Source=EVAN-YPW0LVYKWZ;Initial Catalog=PICTest;Integrated Security=True" />
<commandText value="spLogEntryAdd" />
<parameter>
<parameterName value="@dtTimeStamp" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@szLogger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@szLevel" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@szThread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@szMessage" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@szException" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="AdoNetAppender_SqlServer" />
</root>
<logger name="RRR.LoggingManager">
<level value="INFO" />
</logger>
</log4net>

Thanks,

Evan
Requesting Gravatar... Daniel Jun 26, 2006 8:20 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Evan,

It may be the config file is not being detected (assuming you use a separate log file, as Haaked illustrates above).

Make sure you have an AssemblyInfo.cs file in your App_Code folder with the required [assembly: log4net.Config.XmlConfigurator...] bit adjusted for your application.

Hope this helps...

Daniel
Requesting Gravatar... Lin Jul 07, 2006 6:18 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
I tried this sample code and set it up. But there is no log file created. Could someone here help me out?
Requesting Gravatar... rnet Jul 10, 2006 10:54 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
I also tried this code but there is no log file created.
Requesting Gravatar... kode Jul 14, 2006 11:40 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
If no log file is created, check your Log4net.config. There are three appenders in that. If your SMTP server info is not correct in the config file, log file might not be created. I advise you to remove the first two appenders if you dont need them. Atleast thats what happened in my case.
Hope it helps.
Requesting Gravatar... Ginil Aug 01, 2006 7:01 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Hi,
I am using VS2005, and in my web application, I do not have an AssemblyInfo.cs file. Is that bad?

I have read that it can be put in the global.asax file, but where exactly in it? My gloabal.asax files pretty much contains session_start(), .._end(), application_start(), ..end().

Also, is there an example log4net.config file I can use?

I am new to .NET and ASP.

I need to get log4net working in my web application.

Kind Regards,
Ginil.
Requesting Gravatar... rendomizer Sep 11, 2006 3:23 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
your assemblyinfo.cs and global.asax.cs files are located in the app_code folder of your application.
Requesting Gravatar... you've been HAACKED Sep 27, 2006 2:37 PM
# Log4Net Troubleshooting
Log4Net Troubleshooting
Requesting Gravatar... adam Nov 15, 2006 3:53 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
hi, your example was extremely useful on teh c# project i developed.
do you have a VB.net example of these two lines
[assembly: log4net.Config.XmlConfigurator(
ConfigFile="Log4Net.config",Watch=true )]
and
private static readonly ILog Log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);

your examples are amazingly simple to implement and adapt. a vb translation would save me hours. thanks!!
Requesting Gravatar... Haacked Nov 15, 2006 10:33 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
The first is an assembly level Attribute declaration. I think the syntax is like this:

<Assembly: log4net.Config.XmlConfigurator(
ConfigFile="Log4Net.config",Watch=true )>

Just look up "Attributes" and VB.NET.

The second is probably something like:

Private Shared ReadOnly Log As ILog = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType)

Hope that helps.
Requesting Gravatar... Kaundinya Dec 07, 2006 12:44 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Log4Net is not working for ASP.NET 2.0 when we deployed the web site to the web server.We made sure all the permissions are all proper.

Can anybody help me.It works like a charm local machine but not on the Web Server.

Please Advise...
Kaundinya
Requesting Gravatar... Atiz Mar 07, 2007 12:01 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Hi all,
when I try to use
[assembly: log4net.Config.XmlConfigurator(
ConfigFile="Log4Net.config",Watch=true )]
in the assemblyinfo.cs, the compiler complained that it is not an attribute class. How can I make it work? I am using VS2005 to do my C#.net proj. I've already referenced to log4net.dll.

TIA
Atiz
Requesting Gravatar... PHANI NADIGADDA May 01, 2007 8:52 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Log4Net for logging the messages is working fine for me. The thing is my sessions are getting expired when the I log the message using
log.Debug() or log.Info() or log.Error() or any thing.

Does any know how to overcome this. If, Please help me to get out this issue.

Thanks,
Phani
phani.nadigadda@gmail.com
Requesting Gravatar... yoi May 17, 2007 2:28 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
hallo
Requesting Gravatar... Imtiyaz Jul 06, 2007 5:14 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
I have a ASP.NET 2.0 project in which i have used Log4net 1.2.9.0 configured it through Log4Net.config Files, i have tried to debug, it works fine if i configured my project to use "ASP.NET Development Server", but it did not log any thing if i configured my project to use "IIS Web Server".
In Application_Start event of Global.ASAX
i had put below code.
log4net.Config.XmlConfigurator.Configure(new FileInfo(HttpContext.Current.Server.MapPath(Exact Path)));
Requesting Gravatar... Hemanth Aug 28, 2007 3:14 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
We used Log4net.It was working fine for a long time.But suddenly it stopped writing the log file.can you let me know what may be the cause.

Also,we are using it for two applications.The same folder is configured for the log file.While the log is being created for one folder,the same is not created for the other application
Requesting Gravatar... Scott Dec 02, 2007 9:50 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Make sure that you add the assemblyinfo.cs reference to every project you are emitting debug output from. If you don't you will only get the debug info from the dlls that have this compiled in.
Requesting Gravatar... Miller Jan 18, 2008 2:00 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Hello,

I made this with c#2005 and .net2 on log file n sql2005
now i want to create different log files per day.

thanks in advance

Requesting Gravatar... Miller Jan 18, 2008 4:26 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
here is my code. creates daily logs.. u can custimize it as hourly too. log file name : yyyyMMdd.TXT
use capital letter which are not defined in class.



<root>
<!-- Log Level -->
<level value="ALL" />
<!-- Targets -->
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<!-- Log path -->
<param name="File" value="logs\\" />
<param name="AppendToFile" value="true" />
<!-- Log filename -->
<datePattern value="dd-MM-yyyy.TXT" />
<maxSizeRollBackups value="10" />
<rollingStyle value="Date" />
<maximumFileSize value="1MB" />
<!-- set to false to create daily or hourly logs -->
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %p %u %c %l %m %n" />
</layout>
</appender>
Requesting Gravatar... Sameer Alibhai Feb 06, 2008 3:08 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Here guys, this will explain to you how to set up the configuration in your global.asax or web.config

http://webonweboff.com/tips/asp/logging.aspx
Requesting Gravatar... m May 01, 2008 1:10 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
I've been trying to get log4net to work with asp.net 2.0 and a database table. Here is the config file:

<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

<log4net>
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<!--<add key="Default" value="Database=CJISMNIDb;Server=CJISDEVSQL01;Integrated Security=SSPI;"/>-->
<connectionString value="server=CJISDEVSQL01;database=EventLog;integrated security=true;" />
<commandText value="exec LD80Event_CREATE @eventDate, @logLevel, @message, @exception, @updateUserName" />
<parameter>
<parameterName value="@eventDate" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@logLevel" />
<dbType value="String" />
<size value="512" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%p" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%m" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
<parameter>
<parameterName value="@updateUserName" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%p" />
</layout>
</parameter>
</appender>
<logger name="eventLog">
<level value="ALL" />
<appender-ref ref="ADONetAppender" />
</logger>
<root>
<level value="ALL" />
<appender-ref ref="ADONetAppender" />
</root>
</log4net>

This is the line of code in Global.asax, Application_Start method:
log4net.Config.XmlConfigurator.Configure();

This is in the default page:
private static readonly ILog eventLog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

The issue is all the properties are 'always' set to false when the application is running and nothing is ever written to the database. I have been searching the web for 2 whole days now and I can not find any information that has made a difference.

Can you help with this problem?

Thank you.
Requesting Gravatar... Joe May 07, 2008 9:20 AM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Thanks. That was quick and easy.
Requesting Gravatar... siva May 14, 2008 1:41 PM
# re: Quick and Dirty Guide to Configuring Log4Net For Web Applications
Can anybody tell me how to delete the old log files using log4net. I know using the property "maxsizerollbackups" which is doing the roll back of a file when it reaches to max size.i am using the rolling style as "Date". So every day log file is created but i want to set an option of delete the old files for last 2week or 3 weeks or 10 days like that...
Your help is greatly appreciated..
Thanks
Siva

What do you have to say?

(will show your gravatar)
Please add 5 and 1 and type the answer here: