Click here to Skip to main content
15,887,135 members
Articles / Programming Languages / C#
Tip/Trick

How to Use Log4Net In MVC to Track Error

Rate me:
Please Sign up or sign in to vote.
4.54/5 (8 votes)
1 Nov 2015CPOL2 min read 16.2K   8   5
This tip is to describe how to track error using LOG4Net in MVC project

Introduction

LOG4NET

Before showing what Log4Net is, I would like to explain what logging actually is.

Background

Logging

In computing, a logfile is a file that records either events that occur in an operating system or in a program or when a software runs.

Logging is the act of keeping a log.

Or we can say, logging is a method of tracking/monitoring what is going on when an application is running. Log records will be the most needed items when something goes wrong in your application.

Now I am explaing Log4Net.

LOG4NET

Log4net is an open-source library that allows or helps the .NET applications to trace the details of the errors that have occurred in a project.

Now I will explain how we should use Log4Net in our MVC project to track errors.

Step 1

Create a new MVC project.

Step 2

Go to the tools and make the following changes as in the picture shown:

Image 1

Step 3

Click on the Manage NuGet Package Manager and then search for Log4Net.

Image 2

Step 4

Install Log4Net.

Image 3

Step 5

Image 4

Step 6

Now expand the assembly and you will see the Log4Net.

Image 5

As we have successfully imported Log4Net, we will now use it.

So, create a Home controller with the following Action method.

Using the Code

C#
public class HomeController : Controller  
{  
   log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HomeController));  //Declaring Log4Net  
   public ActionResult Index()  
   {  
      try  
      {  
         int x, y, z;  
         x = 5; y = 0;  
         z = x / y;  
      }  
      catch(Exception ex)  
      {  
         logger.Error(ex.ToString());  
      }  
      return View();  
   }     
} 

Since this method has an error because I am trying to divide it by zero, it will raise an error. So I will track the error.

For this, we need to do some setting in web.config. Go to Web.config and paste in the following things.

Under <configurations> in web.config, write the following code:

XML
<configSections>  
<section name="log4net" 
	type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />  
</configSections>  
   
<log4net debug="false">  
<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> 

Here, I am using the image for a better understanding.

Image 6

Now I am explaining the key concepts.

APPENDER: The <appender /> element specifies the name and logger type. It specifies where the information will be logged, how it will be logged and under what circumstances the information will be logged. You can check the various types of appenders in the following link: http://logging.apache.org/log4net/release/config-examples.html

  • param name: Specifies the file name and path where the log will be saved. In this case, it is "test.log".
  • layout: The Layout element tells Log4Net how each log line should look like.
  • Root: You need to have one root section to house your top-level logger references. These are the loggers that inherit information from your base logger (root).

Now run the project with the Index action method and Home controller and check the log file in C\Test\Test.log. You will get the details of the exception.

Image 7

Since I run it multiple times, it is showing the same error multiple times with the date and time. So in this way, we can use this Log4Net to track errors in a realistic scenario.

Points of Interest

I have a lot of interest in learning new technologies and sharing new code.

History

  • 1st November, 2015: Initial version

License

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



Comments and Discussions

 
GeneralMy vote of 5 Pin
darkliahos2-Nov-15 22:43
darkliahos2-Nov-15 22:43 
SuggestionSome suggestions Pin
ahagel2-Nov-15 20:47
professionalahagel2-Nov-15 20:47 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun2-Nov-15 19:14
Humayun Kabir Mamun2-Nov-15 19:14 
SuggestionA little bit better still ... Pin
John Brett2-Nov-15 2:35
John Brett2-Nov-15 2:35 
Suggestiona bit better... Pin
John Torjo1-Nov-15 21:19
professionalJohn Torjo1-Nov-15 21:19 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.