Click here to Skip to main content
15,906,106 members
Articles / Programming Languages / C#
Article

Log Error and Information Messages in Two Different Files

Rate me:
Please Sign up or sign in to vote.
4.20/5 (2 votes)
7 May 2007CPOL2 min read 59.1K   343   26   8
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:

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

    XML
    <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.

    C#
    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:

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

    C#
    // 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)


Written By
Web Developer
India India
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.

Comments and Discussions

 
QuestionLine No in log file Pin
WebMaster9-Oct-12 20:49
WebMaster9-Oct-12 20:49 
QuestionSend email for only Error level provider in log4net Pin
PankajSaha15-Feb-12 3:00
PankajSaha15-Feb-12 3:00 
SQL
I am using the FILE and SMTP appender and want to log all types of Level (DEBUG, INFO,WARN, FATAL, ERROR) in the file and send the email only for the ERROR. How it can be achieved?
Is there anyway to use the different filters for both the Appender?

I have used the following configuration but it's not working

 <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <to value="myemail.com"/>
      <from value="testemail.com"/>
      <!--<subject value="test logging message"/>-->
      <subject type="log4net.Util.PatternString" value="%property{log4net:HostName} Error: %appdomain" />
      <smtpHost value="SMTP.server.com"/>
      <bufferSize value="512"/>
      <!--<lossy value="true"/>-->
      <!--<evaluator type="log4net.Core.LevelEvaluator">
        <threshold value="ERROR"/>
      </evaluator>-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline"/>
      </layout>
      <filter type="log4net.Filter.LevelMatchFilter">
        <!--<levelToMatch value="ERROR"/>-->
        <levelMin value="WARN" />
        <levelMax value="ERROR" />
      </filter>
    </appender>

GeneralLog4Net config Pin
Ravindra_sagar30-Sep-07 21:31
Ravindra_sagar30-Sep-07 21:31 
Questionlog files Pin
smuzair27-May-07 21:29
smuzair27-May-07 21:29 
AnswerRe: log files Pin
smuzair27-May-07 23:30
smuzair27-May-07 23:30 
GeneralGood start Pin
Zoltan Balazs8-May-07 23:30
Zoltan Balazs8-May-07 23:30 
GeneralRe: Good start Pin
Pallavi Bhoite8-May-07 23:59
Pallavi Bhoite8-May-07 23:59 
GeneralRe: Good start Pin
Ravindra_sagar30-Sep-07 21:32
Ravindra_sagar30-Sep-07 21:32 

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.