# Visual Basic > Visual Basic FAQs >  ASP.Net - How do I add logging to my Web Application using log4net?

## gep13

The log4net assemblies can be found here:

http://logging.apache.org/log4net/index.html

log4net is a port of log4j specifically for use within .Net applications.  It can equally be used for Windows Applications and Web Applications.

The following steps detail what you need to do to add logging capabilities to your application.

 Download the log4net binary - http://logging.apache.org/log4net/download.html Extract the downloaded zip file In your application, add a reference to the following assembly:



```
incubating-log4net-1.2.10\log4net-1.2.10\bin\net\2.0\release\log4net.dll
```

 Open you web.config file and add the following node in the configuration | configSections node:


vb.net Code:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
 Then, within the configuration node, and the following log4net configuration node:


vb.net Code:
<log4net>    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">      <file value="Logs/Application.log" />      <appendToFile value="true" />      <immediateFlush value="true" />      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />      <rollingStyle value="Size" />      <maximumFileSize value="10MB" />      <maxSizeRollBackups value="5" />      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%newline[%date{dd MMM yyyy HH:mm:ss.fff}](%thread) %-5level: %message (%location)%newline" />      </layout>    </appender>    <root>      <level value="DEBUG" />      <appender-ref ref="RollingFileAppender" />    </root>  </log4net>

The above node is fully configurable, and you will find numerous examples here.  It is possible for instance to create multiple appenders, one for logging to a file, one for the System Event Log, log to an email address, etc.  It really just depends on what you want to set up. 

The above simply creating a rolling log file, at Logs/Application.log.  It allows a maximum log file size of 10MB and keeps 5 historical log files.  I have also set the log level at DEBUG, meaning that I want all log messages to be recorded.  In production servers, you can choose to reduce the amount written to the log file by changing this value to either WARN, INFO or ERROR. If you do not already have one, add a Global Application Class to your project (Right click on your project, select Add | New Item, then choose "Global Application Class" from the Templates, and leave the default name) Add the following import to the top of the Global.asax.cs:



```
using log4net;
```

 Declare the following private member:



```
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
```

This is the actual log instance that we will use to write out to our log file I typically add the following code, so that I get information about the application starting and stopping and sessions starting and stopping:



```
        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Debug("Application Starting");
        }

        protected void Application_End(object sender, EventArgs e)
        {
            log.Debug("Application Ending");
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            log.Debug("Session started");
            log.DebugFormat("Session ID: {0}", HttpContext.Current.Session.SessionID);
        }

        protected void Session_End(object sender, EventArgs e)
        {
            log.Debug("Session stopped");
            log.DebugFormat("Session ID: {0}", HttpContext.Current.Session.SessionID);
        }
```

 At this point, we can start our application, and within the root folder of our application, you will find a Logs Folder, with an Application.log file, which contains the following lines (or very similar):



```

[15 Dec 2009 12:56:15.825](4) DEBUG: Application Starting (CS2008WebApplicationLog4netEnabled.Global.Application_Start(C:\temp\CS2008WebApplicationLog4netEnabled\CS2008WebApplicationLog4netEnabled\Global.asax.cs:18))

[15 Dec 2009 12:56:18.215](4) DEBUG: Session started (CS2008WebApplicationLog4netEnabled.Global.Session_Start(C:\temp\CS2008WebApplicationLog4netEnabled\CS2008WebApplicationLog4netEnabled\Global.asax.cs:28))

[15 Dec 2009 12:56:18.246](4) DEBUG: Session ID: twwth1fx5cus1mnftyeyrvvn (CS2008WebApplicationLog4netEnabled.Global.Session_Start(C:\temp\CS2008WebApplicationLog4netEnabled\CS2008WebApplicationLog4netEnabled\Global.asax.cs:29))
```



What happens next, how do we add logging to the rest of our application?  

Well all you need to do is add the same using statement to each code file you want logging in, and also declare the private member for the log variable on each page, and away you go.

You can expert with using:



```
log.Debug("Debug Message");
log.Error("Error Message", ex);
log.Fatal("Fatal Message", ex);
log.Info("Info Message");
log.Warn("Warn Message");
```

Notice that it is possible to pass an exception to the methods as well.  log4net will then write out the stack trace for you into the log file, which is very useful when debugging.

*Lesser known feauture*

One lesser known feature regarding log4net is that you can actually configure different log files for different portions of your application.  Let's say you have the following namespaces in your application:



```
CS2008WebApplicationLog4netEnabled.BLL
CS2008WebApplicationLog4netEnabled.DAL
```

Where the first is your Business Level Logic, and the second is your data access layer.  They may exist within the same assembly, but because of the separation of logic, you might actually want the log messages to also be separated.  To achieve this, you can create two appenders, and only write the log messages from each namespace out to the correct appender.  Here is an example configuration node where this is set up:


vb.net Code:
<log4net>    <appender name="RollingFileAppenderDAL" type="log4net.Appender.RollingFileAppender">      <file value="Logs/BLL.log" />      <appendToFile value="true" />      <immediateFlush value="true" />      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />      <rollingStyle value="Size" />      <maximumFileSize value="10MB" />      <maxSizeRollBackups value="5" />      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%newline[%date{dd MMM yyyy HH:mm:ss.fff}](%thread) %-5level: %message (%location)%newline" />      </layout>    </appender>     <appender name="RollingFileAppenderDAL" type="log4net.Appender.RollingFileAppender">      <file value="Logs/DAL.log" />      <appendToFile value="true" />      <immediateFlush value="true" />      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />      <rollingStyle value="Size" />      <maximumFileSize value="10MB" />      <maxSizeRollBackups value="5" />      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="%newline[%date{dd MMM yyyy HH:mm:ss.fff}](%thread) %-5level: %message (%location)%newline" />      </layout>    </appender>           <root>         </root>     <logger name="CS2008WebApplicationLog4netEnabled.BLL" additivity="false">      <level value="DEBUG" />      <appender-ref ref="RollingFileAppenderBLL" />    </logger>     <logger name="CS2008WebApplicationLog4netEnabled.DAL" additivity="false">      <level value="DEBUG" />      <appender-ref ref="RollingFileAppenderDAL" />    </logger>  </log4net>

Notice, that the two appenders are specifically filtered to look only for log messages that come from the different namespaces of your application

----------

