Error Logging Using Log4Net in Web Application


In this article we will see how to log errors using Log4Net in a web application.

Step 1

Open Visual Studio 2013.

Step 2

Go to the "File" menu then select "New" and click on "Project...".

new Project

Step 3

Select "Web" from the left panel, then "ASP.NET Web Application".

Provide an appropriate application name and select the Location.

Press the "OK" button.

Web Application

Step 4

Select "Empty" and check the "Web Forms" check box.

Press the "OK" button.

Empty Web Forms

Step 5

Right-click on the project then select "Add" and click on "New Folder".

New Folder

Step 6

Provide the folder name as "Lib". This folder is used to copy Log4Net.dll.


Step 7

Copy "log4net.dll" to the Lib folder. You can find this DLL in the downloads.


Step 8

In order to add a reference, right-click on "References" and select "Add Reference".

add reference

Step 9

Select "log4net.dll" from the Lib folder.


Step 10

The reference is added under "References".


Step 11

Add the following code snippet to the web.config file.

web config

Step 12

In the web.config file, we set the file value as "LogBackUp". So create a folder with the same name in the root directory.

Right-click on the project, expand "Add" and click on "New Folder".

add new folder

Step 13

Name it "LogBackUp".

LogBackUp folder

Step 14

Configure log4net in the Application_Start event.

Application Start event

Step 15

Now right-click on the project, select "Add" and click on "New Item".

add New Item

Step 16

Select "Web Form", provide an appropriate name and click on the "Add" button.

Select Web Form

Step 17

Add the following code snippet to the "WebForm1.aspx.cs" file. Here we throw an exception intentionally to catch the exception and log it.


Step 18

Run the application and it creates a log file under "LogBackUp".


Step 19

Open the .Err file and you can see that the exception message is successfully logged.

exception message

Similar Articles