Using Log4Net in an ASP.Net application

In this post I would like to show you a fairly simple example on how to use Log4Net logging service to log information in a text file.You can log information to a text file,a database table or Windows event viewer using the Log4Net logging assembly.This can be done through the various appenders.Have a look here to see a list and configurations for built-in appenders. 

I have been using various ways to implement logging when was that required in an ASP.Net application. I used the Enterprise Library Logging Application Block but only recently I discovered how easy and flexible Log4Net is.It is very easy to use, well documented and open source (Apache Software Foundation). I will create a very simple example where I open a connection to a database and print on the screen a simple message, if the connection was opened successfully or not. At the same time I will log various information to a text file.

I assume that you have access to a version of SQL Server and Northwind database.

If you do not, you can download and install the free SQL Server Express edition from here. If you need the installation scripts for the sample Northwind database, click here

1) Launch Visual Studio 2010/2008/2005 (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose C# as the development language.

2) Add a new item to your site, a web form. Leave the default name, Default.aspx

3) Add ASP.Net folder in your site, App_Code. Add another folder inside the App_Code special folder and name it DataAccess.

4) Go to View - > Server Explorer (Database Explorer) and add a connection to the Northwind database.You have just to set the instance of the SQL Server and the name of the database.Test the connection.

5) In your web.config (which is pretty much empty) add a <connectionStrings>. Ιn my case it like the one below. In your case you must set the Data Source property to your SQL server instance.

 

<connectionStrings>
<add name="NorthwindConnectionString" 
connectionString="Data Source=.;Initial Catalog=Northwind;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
 

6) Add a class file inside the DataAccess folder. Name the file Connection.cs.So we have a Connection class. The code for the whole class is 

 

public class Connection
{

public static SqlConnection GetDBConnection()
{
      
string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].

ConnectionString;

SqlConnection connection = new SqlConnection(connectionString);

      
connection.Open();
return connection;
    }

}

This is very simple static method. It returns an SQL connection.Inside this method I do the following.

 

  • I get the connection string from the configuration file

  • I create a new connection object

  • I open the connection and return the connection object. 

Do not forget to add these lines of code in the top of the file. 

 

using System.Data.SqlClient;

using System.Configuration;
 

7) In the Default.aspx page add a Label control. Leave the default name.

8) Do not forget to add this line of code in the top of the Default.aspx.cs file

 

using System.Data.SqlClient;
9) We need to add the Log4Net assembly to our website.I will use VS to add this assembly to our website.  From visual studio Tools –> Library Package Manager –> Manage NuGet Packages… In Manage NuGet Packages… windows, search Log4Net then install log4net package to your project.The log4net.dll will be added to the Bin folder.Have a look at the picture below
 
10) Add a new item to your application, a Global.asax file.In the Application_Start() type  
    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup
 
        log4net.Config.XmlConfigurator.Configure();
 
    } 

 We initialise log4net at application start up.

11) We need to make changes to the web.config file.I provide the information where log4net configuration parameters are defined.

In the configSections type the following

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

 

Now we need to add more settings in the web.config regarding the LogFileAppender and the path to the actual log file. Type the following in the web.config file

   <log4net>
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
          
    <param name="File" value="C:\test\test.log"/>
    <!--<param name="AppendToFile" value="true"/>-->
      <layout type="log4net.Layout.PatternLayout">
  <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
            </layout>
        </appender>
 
 
        <root>
            <level value="All" />
            <appender-ref ref="LogFileAppender" />
        </root>
    </log4net>

 

The complete web.config follows.

 

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
<section name="log4net" 
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/>
  </configSections>
 
 
 
 
        <connectionStrings>
            <add name="NorthwindConnectionString"
            connectionString="Data Source=.;Initial Catalog=Northwind;
Integrated Security=True" providerName="System.Data.SqlClient" />
        </connectionStrings>
 
 
    <log4net>
 <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
     
    <param name="File" value="C:\test\test.log"/>
   <!--<param name="AppendToFile" value="true"/>-->
   <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
   </layout>
 </appender>
 
 
        <root>
            <level value="All" />
            <appender-ref ref="LogFileAppender" />
        </root>
    </log4net>
 
 
    <system.web>
    <compilation debug="true" targetFramework="4.0"/>
 
  </system.web>
</configuration> 
 
 12) In the Page_Load event handling routine of the Default.aspx page type 
 protected void Page_Load(object sender, EventArgs e)
    {
  log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default));
 
        if (!IsPostBack)
        {
            Label1.Text = "We will test the connection to the database.";
 
            try
            {
         logger.Info("Open Connection ");
       
        SqlConnection connection = Connection.GetDBConnection();
        connection.Close();
    Label1.Text = "We opened and closed the connection to the database";
    logger.Info("We opened and closed the connection to the database");
            }
            catch (SqlException ex)
            {
 
  Label1.Text = "We cannot connect to the database" + ex.Message;
 
  logger.Error("Error in opening the connection");
              
            }
        }
 
    }

The code is very easy to understand. We create an instance of the log4net object and use the Info and Error methods to log the information to the text file.

Do not forget to add this line of code

using log4net;

 
in the top of your file.
13) Run your application and then have a look at the test.log file.Have a look in the picture below to see what was logged when I run the example
 
  
I ran the application the first time and everything was successful and the information I wanted was logged.The second time I intentionally changed the connection string to point to a non-existing SQL Server instance and then run again the application.This time the error message was logged in the log file.
Hope it helps!!!
 

5 Comments

Comments have been disabled for this content.