2012-10-26

Configure log4net with asp.net (Logging with asp.net)

Logging is a very important thing for a web site specially if the website is on live! It will help you to debug your live web application without needing to enable remote debug on the server, so it comes very handy when you need to log the errors which can occur at the live site, when users are using it.

So here I’m going to explain how to configure log4net with a website built on asp.net.

1. Download the log4net dll file from here.

2. Add the log4net.dll file to your project

3. Add reference to the log4net.dll file in your project.

4. Add the below section at the top of your web.config file (right after you open the <configuration> section).

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

5. Add the below section to your web.config file within the <configuration> section.

<log4net>
  <root>
    <level value="Debug"/>
    <appender-ref ref="LogFileAppender"/>
  </root>
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="C:\CentralCMS_Logs\Logs.txt"/>
    <param name="AppendToFile" value="true"/>
    <rollingStyle value="Size"/>
    <maxSizeRollBackups value="10"/>
    <maximumFileSize value="3MB"/>
    <staticLogFileName value="true"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline"/>
    </layout>
  </appender>
  <logger name="CentralCMS">
    <level value="DEBUG"/>
  </logger>
</log4net>

  • I’ve defined the level as ‘Debug’ since I just need to debug my application. If you need to stop the application or need something like that when an error occurs, you should go for a level like ‘Fatal’.
  • I’ve used appender type as log4net.Appender.RollingFileAppender. So it will roll the log files based on rollingStyle. In this example, ‘Size’.
  • Here, you can set the path where you need log files to be saved by specifying the parameter name ‘File’. In this example, I’m storing them on the directory CentralCMS_Logs in C drive. If there is no directory like that, your program will automatically create a folder.
  • Set ‘AppendToFile’ parameter to ‘true’ if you need the new logs to be appended to the existing log file. If you need to override the old logs with new log, set it to ‘false’.
  • Here I’ve set rollingStyle to the ‘Size’, which means it will roll the file once the maximum File Size reaches. The default value for the rollingStyle is ‘Composite’, which means it will roll the file both depending on the file size and the date. If it reached the maximum file size before the day ends, it will go for a new file. If not, it will open a new file on next day.
  • Here I’ve defined maxSizeRollBackups as 10, which means it will create 10 backup files before the oldest one is erased. Once it reach for 10 files, it will delete the oldest log file and create a new file.
  • As the name suggests, maximumFileSize is the maximum file size for a log file. It will go for a new file when the maximum file size reaches. If the rollingStyle is set to ‘Date’, then it will not log further logs if the maximum file size reaches before the end of the day.
  • I’ve set staticLogFileName to ‘true’ since I want to log on the same file. If you need separate file for each log, set it to false.
  • I’ve set layout type to PatternLayout because I need my own pattern for the log texts. Through the ConversionPattern parameter, I’ve specified my own format for the log texts. I.e.
    • %date - Date and time followed by,
    • [%thread] - thread number which generated the log event followed by,
    • %-5level - level of the logging event (Right pad with spaces if the level of the logging event is less than 5 characters long) followed by,
    • %logger – the logger of the logging event (Global file, Default file etc. with the namespace) followed by,
    • %message – log message followed by,
    • %newline – a new line.

6. In your Global.ascx file, import the log4net class like this

using log4net;

7. Configure log4net at the Application_Start() method like this

void Application_Start(object sender, EventArgs e)
{
     // Code that runs on application startup
     log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
}

Configure method tells the application to configure log4net using this particular config file.

8. To use the logging, initiate a global variable like below in your class where you need to log the information. Note that I’ve passed the logger name I’ve given in the web.config file to the GetLogger() method. It will return a ILog object which you can use to do the logging.

private static readonly ILog log = LogManager.GetLogger("CentralCMS");

In my example, I’m showing how to log all the unhandled exceptions you are getting for your web application. So I’m going to declare this variable in the Global.asax file.

8. Now you can successfully use the log4net for logging. By doing the logging on the Application_Error() method, we can get all the unhandled exceptions like below

void Application_Error(object sender, EventArgs e)
{
     Exception ex = Server.GetLastError();

     log.Debug("++++++++++++++++++++++++++++");
     log.Error("Exception - \n" + ex);
     log.Debug("++++++++++++++++++++++++++++");
}

10 comments:

johan paterson said...

Really good info..thanks


Website design Sydney | website design Melbourne | website design

Vilson said...

I really Enjoy the reading on this post, please continue it.


SEO Sydney | SEO Melbourne | SEO

Len Rivers said...

It will help to debug your stay web program without requiring to allow distant debug on the hosting server, so it comes very useful when you need to log the mistakes which can happen at the stay site.

Ossa's Blog said...

Thanks alot !

Ossa's Blog said...

Thanks !

Suresh Sundar said...

simple example. thanks

Shahid said...

Hi, I have follow your tutorial at youtube and it is really good.

Could you also upload a tutorial about ndc feature in log4net.

I read about ndc but did not understand how to configure and log the info.

What i understand ndc feature help to log the info in a block. for example if multiple user working on the website and also on same page. Then ndc will help to log the info as a block for each user so its not mixing the logs of different user. So If i have info in log file in a block then its really good to troubleshoot the problem.

Anonymous said...

Thanks

Unknown said...

Does this work in ASP.NET Web API's Also? What changes need to be made for it?
Thanks

Ruchira Gamage said...

Yes, it should work in any asp.net application. I haven't tried that on a Web API application but I don't think you need to make any specific changes. Did you try the code as it is in a Web API application?