Click here to Skip to main content
Click here to Skip to main content

Configure Log4Net in ASP.NET 2.0

By , 11 Oct 2006
 

Introduction

Log4net is an Open Source utility used for log/report statements to various kinds of output targets (text file, email, database, event viewer etc.): http://logging.apache.org/. It can be a very handy utility for application instrumentation purposes.

Configuring Log4net

Step 1: Add a reference of Log4net.dll to the project.

Step 2: Add Global.asax to the project, if not already added. In the "Application_Start" event of global.asax, add the following code:

log4net.Config.XmlConfigurator.Configure();

Step 3: In the web.config file, under Configuration->Configsections, add the following section:

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

Step 4: In web.config, add a new section "<log4net>". This section will contain all the settings related to the Log4net configuration.

Step 5: In web.config, under "log4net" section, add the required appenders (output target) configuration sections in the following way:

File appender configuration, used for log statements in a text file
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
  <param name="File" value="Logs\\Log4Net.log"/>
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
  </layout>
</appender>
SMTP appender configuration, used for log statements by sending email
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="" />
<from value="" />
<subject value="" />
<smtpHost value="" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level 
          %logger [%property] - %message%newline%newline%newline" />
</layout>
</appender>

Step 6: In the web.config file, under "log4net" section, for each appender, add loggers in the following way:

<logger name="File">
<level value="All" />
<appender-ref ref="LogFileAppender" />
</logger>
<logger name="EmailLog">
<level value="All" />
<appender-ref ref="SmtpAppender" />
</logger>

Step 7: Now, whenever we want to log any information/error/warning, call the appropriate method in the following manner:

//for logging to file
log4net.ILog logger = log4net.LogManager.GetLogger("File");

//for emailing
log4net.ILog logger = log4net.LogManager.GetLogger("EmailLog");

logger.Info("Starting page load");

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vikramaditya S Shekhawat
Architect
India India
Member
Originally from Jaipur(Rajasthan).
Working in Norway for a Software company.Holding diploma from CDAC and MCSD.NET (C#).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionthanks . for the quick article it helped mememberrama charan13 Jul '11 - 21:34 
thanks . for the quick article it helped me
Rama Charan Prasad
 
"Be happy and Keep smiling...Smile | :) "

QuestionHelped me with PayPal API Medium Trust Issue!memberMember 80371729 Jul '11 - 20:47 
Thanks! This saved me a ton of time trying to figure out a workaround to a trust issue with GoDaddy.com and the PayPal API.
 
In case anyone else is having the issue with PayPal where you're getting the error "That assembly does not allow partially trusted callers" or something similar, I've posted a workaround (* I hope*) here: https://www.x.com/message/203683.
GeneralMy vote of 5memberdaylightdj22 Apr '11 - 4:54 
I'm giving you a 5, because I am using log4net for the first time. I followed the steps outlined in this article and everything worked perfectly. Thanks for taking the time to document.
GeneralMy vote of 5memberoleg_7920 Feb '11 - 21:59 
Great article
GeneralMy vote of 5memberMember 23636832 Jan '11 - 11:16 
Great article. It was taking me awhile to get log4net setup but your article got me up and running instantly.
GeneralMy vote of 4mvpMd. Marufuzzaman9 Nov '10 - 20:17 
Useful work.
GeneralMy vote of 1memberAnuj Tripathi5 Aug '10 - 20:54 
Waste
GeneralRe: My vote of 1memberjeremychild10 Aug '11 - 17:16 
You do better then! Its a good article for beginners.
GeneralUser Level LoggingmemberMember 367943826 Nov '09 - 16:11 
I am using log4net in my apolication but I need to log for individual users who ever acess my web site. I tried to create log files where file name would given dynamically when user logged in. But when one user is active and if the second user logs in, the logs gets appended to first logger and failes to create a new file. Please help.
GeneralBlank Pagememberdhaval.upadhyay9 Feb '09 - 1:17 
Hi I have set as you have suggested but I am getting blank log file.
Am i missing some thing?
 
I am also not accessing this file untill Restarting the visual stodio.
(Message Another Application is using file)
Generallog4net is not working with Access and SQL-Server using ASP.NETmemberBimal Kothari13 Aug '08 - 4:33 
Hi,
 
Can I have complete sample to insert log data in to Access and SQL-Server.
 
I have verified that log4net is not working with Access and SQL-Server using ASP.NET after making all
configuration correct and proper.
 
Please provide me complete sample if it possible soon.
 
Thanks,
Bimal
Generallog4net is not working with Access and SQL-ServermemberBimal Kothari13 Aug '08 - 4:32 
Hi,
 
Can I have complete sample to insert log data in to Access and SQL-Server.
 
I have verified that log4net is not working with Access and SQL-Server using ASP.NET after making all
configuration correct and proper.
 
1.
Here is my config file:
------------------------------------------------------------------------------------------------




<!-- This section contains the log4net configuration settings -->














































<!--Levels - OFF, ALL, WARN, FATAL, INFO, ERRROR, DEBUG -->




 

------------------------------------------------------------------------------------------------
 
Please provide me complete sample if it possible soon.
 
Thanks,
Bimal
GeneralNeed log4net Solution and sample for Access and SQL-ServermemberBimal Kothari13 Aug '08 - 4:30 
Hi,
 
Can I have complete sample to insert log data in to Access and SQL-Server.
 
I have verified that log4net is not working with Access and SQL-Server using ASP.NET after making all
configuration correct and proper.

Please provide me complete sample if it possible soon.
 
Thanks,
Bimal
GeneralSecurity ExceptionmemberManojkumar Sharma6 Jun '08 - 0:49 
I am facing security exception in asp.net 2.0. Below is the error
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
 
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
 
Source Error:
 

Line 5: void Application_Start(object sender, EventArgs e)
Line 6: {
Line 7: log4net.Config.XmlConfigurator.Configure();
Line 8:
Line 9: }

Can anyone pls guide?
Generalhimembermanoj221849 May '08 - 2:59 
Thanks for your code and explanation but can you please tell me some more clear please i dnt have somuch experience please helpm me regarding this.
 
Thank you in advance
 
M.MANOJ
 
manoj22184@gmail.com
GeneralThanks !memberandy_sinclair1 Nov '07 - 5:49 
I was using various bits and pieces from other sites to try and get logging of components working within ASP.NET. Nothing was working, but your checklist (especially the global.asax) did the trick !
 
Andy
GeneralThank you, it's helpful!memberliuruicai11 Oct '07 - 16:21 
Thank you, it's helpful!
Generalblank filememberRADman10 Oct '07 - 4:26 
Hello,
 
I have tried to implement this solution and I do get an empty log file in my logs folder, but nothing ever gets written to it, can you perhaps hit the main items that I need to investigate to make sure I have it configured correctly?
 
Thanks.
GeneralWhere should i add the new sectionmembersatyamythily26 Jul '07 - 6:00 
Hi,
where should i add a new section. please help me at point numner 4...i mean under which configuration i have to add the . can u please explain me with an example so that it will be helpful for me,
if i add it under the it is giving me the error. where ever it is giving me the error.
Thanks
mythily
GeneralRe: Where should i add the new section [modified]memberNoman Mohammad6 Aug '07 - 6:33 
Firstly you have to add a section under configSections. If you dont have the configSections then add it right after configuration. Example:
 
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/<
</configSections&;gt
Once you have added that section then you add <log4net> section just after appSettings and connectionString for example:
 
<appSettings>
your code...
</appSettings>
<connectionString> -- if you have this section add after this or just after appsettings
</connectionString>
 
Now ADD:
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="D:\example.log"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<datePattern value="yyyyMMdd"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>

<root>
<level value="DEBUG"/>
<
 
Nom84
 

 
-- modified at 12:43 Monday 6th August, 2007
GeneralNicemembernsebastian20 Jun '07 - 11:47 
Your article help me a lot. You must a god damn genious
GeneralBest log4net guide I foundmemberreach4thelasers28 May '07 - 6:57 
Hey, thanks for this! Very well written and easy to follow - even for a complete beginner. I've seen a few log4net guides on code project, I think this is by far the best one.
 
Thanks again,
 
Kevin.
QuestionlogsmemberLeleHalfon8 May '07 - 6:55 
where is the folder Logs ?
should i create it?
GeneralThank-you!memberGarbage Can10 Dec '06 - 13:00 
Thank-you for this article. It was difficult to quickly find info on setting up Log4Net within .NET 2 but your article efficiently explained the process. Thank-you and very much appreciated.
GeneralXmlConfiguratorAttributtememberTomO217 Oct '06 - 3:57 
Another way to start up logging is to use log4net.Config.XmlConfiguratorAttribute:
 
[assembly : XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
 
With this attribute in your application (I put it in the AssemblyInfo.cs), log4net will use the file Log4Net.config instead of web.config. The Watch=true tells log4net to keep an eye on the file for changes.
GeneralRe: XmlConfiguratorAttributtememberdnh11 Apr '07 - 4:28 
Very Cool | :cool:
 

"Throughout human history, we have been dependent on machines to survive. Fate, it seems, is not without a sense of irony. " - Morpheus
"Real men use mspaint for writing code and notepad for designing graphics." - Anna-Jayne Metcalfe

GeneralRe: XmlConfiguratorAttributtemembertodeti23 Oct '07 - 6:44 
But we can't find assemblyinfo file in .net 2.0
GeneralClosing log filesmemberDejan Grujic16 Oct '06 - 22:29 
This is all basic log4net setting. You've missed one important thing that's not very well documented and therefore much more useful:
 
protected void Application_End(Object sender, EventArgs e)
{
LogManager.Shutdown();
}

 
Before I added this I had cases when logs were not working any more after web application was restarted because log files were not unlocked properly.
GeneralRe: Closing log filesmemberVikramaditya S Shekhawat16 Oct '06 - 22:32 
I never faced this problem, but its always good to have such clean up code.
Thanks DejanSmile | :)
GeneralDirectory write permissionsmemberRodrigo Dias16 Oct '06 - 1:36 
By the way, you have to add write permissions to the destination directory is the asp.net folder for the FileAppenders, i.e., in your configuration you are writing the log files to the directory "Logs". You have to add write permissions to the directory for the ASP.NET user.
At least for me i had to do that....
GeneralRe: Directory write permissionsmemberVikramaditya S Shekhawat16 Oct '06 - 1:39 
yes,
you are correct.
GeneralRe: Directory write permissionsmemberKrishanChaminda19 Oct '06 - 14:11 
Hi
 
Has anyone used a network path to store the Log?. I need to use a network location. i hav given rights to this folder but i still cant write a log entry.
 
Cheers
cK

Generalweb.configmemberVladimir_V13 Oct '06 - 8:05 
Could you attach configured Web.config file please.
 
Thanks,
Vladimir
GeneralRe: web.configmemberVikramaditya S Shekhawat14 Oct '06 - 21:12 
Sure, will attach it on Monday, 16-Oct
 
Thanks
Vikram
GeneralRe: web.configmemberdarkrd3 Nov '06 - 17:25 
You can find more information and log4net examples in www.dotnetspace.com :->

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 11 Oct 2006
Article Copyright 2006 by Vikramaditya S Shekhawat
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid