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
-
Add a reference to log4net DLL in your project. You can get this DLL in the source code zip.
-
Add App.config file in your project. For Web, add web.config.
-
Under <configuration>
tag, add <configSections>
tag and write the following code:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
-
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>
-->
<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.
-
End <configuration>
tag.
-
Now open project solution and insert one textbox
with label "Insert numbers only" and button on form.
-
In the class declaration, initialize logger. It allows us to record class, method and line number automatically.
ILog logger = LogManager.GetLogger(typeof(Form1));
-
In the constructor, configure the DOMConfigurator
.
For Web, you can declare it in the Application_Start
event of Global.asax:
log4net.Config.DOMConfigurator.Configure();
-
On button click, add the following code:
logger.Debug("start btnShow_Click");
try
{
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);
}
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
- It logs messages in a good format, you can change the format to suit your needs.
- You can change Filter options to customize error recording.
History
- 7th May, 2007: Initial post