Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Configure Log4Net in ASP.NET 2.0

0.00/5 (No votes)
11 Oct 2006 1  
How to configure Log4Net in an ASP.NET 2.0 application.

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here