Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Log Error and Information Messages in Two Different Files

0.00/5 (No votes)
7 May 2007 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here