Click here to Skip to main content
Licence CPOL
First Posted 7 May 2007
Views 22,299
Downloads 64
Bookmarked 25 times

Log Error and Information Messages in Two Different Files

By | 7 May 2007 | Article
Using log4net, we can write error mesages and information messages in two different files.

Introduction

In this code, we are using log4net to log error messages and information / debug messages in two different files, Error.txt and Info.txt. We can use this in both, Windows and Web applications.

Background

log4net is a free utility. I am using log4net 1.2.10. You can download it from here.

Using the Code

  1. Add a reference to log4net DLL in your project. You can get this DLL in the source code zip.

  2. Add App.config file in your project. For Web, add web.config.

  3. Under <configuration> tag, add <configSections> tag and write the following code:

    <configSections>
    <section name="log4net" 
    type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
  4. Under <configuration> tag, add <log4net> tag and write the following code:

    <log4net>
    <appender name="InfoRollingLogFileAppender" 
    	type="log4net.Appender.RollingFileAppender,log4net">
    <param name="File" value="C:\\Info.txt" />
    <param name="AppendToFile" value="true" />
    <param name="MaxSizeRollBackups" value="10" />
    <param name="MaximumFileSize" value="10240KB" />
    <param name="RollingStyle" value="Size" />
    <param name="StaticLogFileName" value="true" />
    <param name="Threshold" value="DEBUG"/>
    <layout type="log4net.Layout.PatternLayout,log4net">
    <param name="ConversionPattern" value="%p [%d{dd MMM HH:mm:ss}][%l]- %m%n" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="DEBUG" />
    <levelMax value="DEBUG" />
    </filter>
    <filter class="log4net.Filter.DenyAllFilter"/>
    </appender>
    <appender name="ErrorRollingLogFileAppender" 
    	type="log4net.Appender.RollingFileAppender,log4net">
    <param name="File" value="C:\\Error.txt" />
    <param name="AppendToFile" value="true" />
    <param name="MaxSizeRollBackups" value="10" />
    <param name="MaximumFileSize" value="10240KB" />
    <param name="RollingStyle" value="Size" />
    <param name="StaticLogFileName" value="true" />
    <param name="Threshold" value="ERROR"/>
    <layout type="log4net.Layout.PatternLayout,log4net">
    <param name="ConversionPattern" value="%p [%d{dd MMM HH:mm:ss}][%l]- %m%n" />
    </layout>
    <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="WARN" />
    <levelMax value="ERROR" />
    </filter>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
    <level value="debug" />
    <appender-ref ref="InfoRollingLogFileAppender" />
    <appender-ref ref="ErrorRollingLogFileAppender" />
    </root>
    </log4net>

    Here, I am using the RollingFile Appender which stores 1024KB of data in the file. After that, it will create a new file... after 10 files (maxsizerollbackup), it will overwrite the existing one.

    In the layout, conversion pattern is used:

    • %p - will show the level of message
    • %d - will show the date
    • %l -will show the class, method and line number where error occurred and
    • %m - will show the message to display

    I am using LevelRangeFilter to filter messages to send to specified files. e.g. Error messages to Error.txt and debug messages to Info.txt.

    In Root tag, set the default level for message recording and appender to reference.

  5. End <configuration> tag.

  6. Now open project solution and insert one textbox with label "Insert numbers only" and button on form.

  7. In the class declaration, initialize logger. It allows us to record class, method and line number automatically.

     ILog logger = LogManager.GetLogger(typeof(Form1));//class name 
  8. In the constructor, configure the DOMConfigurator.

    For Web, you can declare it in the Application_Start event of Global.asax:

     log4net.Config.DOMConfigurator.Configure();
  9. On button click, add the following code:

    // record debug message and send it to Info.txt
    logger.Debug("start btnShow_Click");  
    
    try
    {
     //convert text box value to int. 
     //If it's not a number, then it will throw an error. 
      int i = Convert.ToInt32(txtShow.Text);  
      MessageBox.Show(i.ToString(),"Logger Demo"); 
    }
    catch (Exception ex)
    {
     MessageBox.Show("Error Occurred , please check error log file !", "Logger Error");
     logger.Error(ex);      // record error message and send it to Error.txt
    }
     logger.Debug("End btnshow_Click");

OutPut

Error.txt Output

ERROR [02 May 17:22:26][Logger.Form1.btnShow_Click
	(E:\codeProject\Logger\Logger\Form1.cs:35)]- System.FormatException: 
	Input string was not in a correct format.
   at System.Number.StringToNumber(String str, NumberStyles options, 
	NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Convert.ToInt32(String value)
   at Logger.Form1.btnShow_Click(Object sender, EventArgs e) in 
	E:\codeProject\Logger\Logger\Form1.cs:line 29

Info.txt Output

DEBUG [02 May 17:22:24][Logger.Form1.btnShow_Click
	(E:\codeProject\Logger\Logger\Form1.cs:26)]- start btnShow_Click
DEBUG [02 May 17:22:26][Logger.Form1.btnShow_Click
	(E:\codeProject\Logger\Logger\Form1.cs:37)]- End btnshow_Click

Points of Interest

  1. It logs messages in a good format, you can change the format to suit your needs.
  2. You can change Filter options to customize error recording.

History

  • 7th May, 2007: Initial post

License

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

About the Author

Pallavi Bhoite

Web Developer

India India

Member

Working as software developer from last 3 year.
I am handling Windows,Web Application with C# (Visual studio 2005) and SQL server 2005. I am MCTS - Web Application 2.0 and MCPD - Web developer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionSend email for only Error level provider in log4net PinmemberPankajSaha3:00 15 Feb '12  
GeneralLog4Net config PinmemberRavindra_sagar21:31 30 Sep '07  
Questionlog files Pinmembersmuzair21:29 27 May '07  
AnswerRe: log files Pinmembersmuzair23:30 27 May '07  
GeneralGood start PinmemberZoltan Balazs23:30 8 May '07  
GeneralRe: Good start PinmemberPallavi Bhoite23:59 8 May '07  
GeneralRe: Good start PinmemberRavindra_sagar21:32 30 Sep '07  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 8 May 2007
Article Copyright 2007 by Pallavi Bhoite
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid