Introduction
This blog provides complete guidelines and best practice by demonstration on how to use log4net in C# with code example. We will also discuss the various methods provided by the log4net library for different log level and the appenders for storing log messages in different source.
How to use log4net in C#
Getting Started
The log4net is the most common and popular used logging framework in Microsoft projects. To make your application smooth and faster you need to diagnose your application, log4net provides an environment to track your application activities and record logs or activities in different sources like a file or database.
The main component of log4net is LogLevels and Appenders, The log4net provides various methods and appenders to record logs messages at different levels and in different sources.
log4net Log Levels
All log messages written through log4net must be assigned one of the five among following log4net level:
- Debug:- Will print message at the time of debugging project only.
- Info:- Used to record information type message.
- Warn:- Used to log warnings.
- Error:- Used to record errors or exception.
- Fatal:- Used to print fatal error messages.
log4net Appenders
An log4net appender is a name for what logs the information. It specifies where the information will be logged, how it will be logged, and under what circumstances the information will be logged.
log4net ConsoleAppender
It writes to the output window, or the command window if you are using a console application.
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%thread] %level %logger - %message%newline"/>
</layout>
<filter type="log4net.Filter.StringMatchFilter">
<stringToMatch value="test" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
</appender>
log4net File Appender
This appender will write log messages into a text file.
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="mylogfile.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
log4net RollingFileappender
The purpose of the rolling file appender is to perform the same.
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="mylogfile.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
log4net AdonetAppender
Appender used to record log messages in the database.
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection,
System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=[database server];
initial catalog=[database name];integrated security=false;
persist security info=True;User ID=[user];Password=[password]" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],
[Message],[Exception]) VALUES (@log_date, @thread, @log_level,
@logger, @message, @exception)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
Demonstration:- Steps to use log4net
Open your source code in which you want to implement log4net.
Go to Solution Explorer, then right click on the project name->open Manage NuGet Package for solution by right clicking on
Manage NuGet Package...
Click on the Brose tab, then search for log4net. Install the latest version.
Or you can install it, by Manage NuGet Console by using below command. It will automatically install the latest version
Install-Package log4net
Again go to Solution Explorer, then expand the Properties. You will find it just below your project name.
Double click on the AssemblyInfo.cs to open it and paste the below code just after the AssemblyCulture code.
[assembly: log4net.Config.XmlConfigurator]
Your code placement should look like below code.
[assembly: AssemblyCulture("")] [assembly: log4net.Config.XmlConfigurator]
Open the .config file of your project, then find the <configSections></configSections> tag, if you don't find added the <configSections> tag, then copy the below code and past it just after the </configuration> tag.
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> </configSections>
If the config Sections tag already there, then copy the below code and paste it just after the <configSections> tag.
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
Find the </configuration> tag and paste below code just before the </configuration> tag. This is the log level and appender setting in config for log4net, The code should place between <configuration> and </configuration> tag.
<log4net> <appender name="TestAppender" type="log4net.Appender.RollingFileAppender"> <file value="D:\Scanid\Mlogs.log" /> <encoding value="utf-8" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date- %message%n" /> </layout> </appender> <root> <level value="All" /> <!-- If the following line is not included the log file will not be created even if log4net is configured with this file. --> <appender-ref ref="TestAppender" /> </root> </log4net>
log4net Configuration
Create a new static class in your project and rename it to ‘Logger’.
Code of logger class given in the below of this blog and replace it with your logger class code which is you created just before.
Note that the reason behind is to make the class as static that to use commonly in different classes in projects. You can write your own logic in the methods or you can create new methods inside the class to implement your own logic.
Invoke the methods of logger class to log messages for your project. For example, to write the exception messages invoke the Error function in the catch block.
public void Test() { Logger.Info("Test method execution started"); try { Logger.Info("try block executed"); } catch(Exception ex) { Logger.Error(ex); } finally { Logger.Info("Finally block executed"); } Logger.Info("Test method execution completed"); }
Now you are done with the implementation of log4net, build your project.
log4net C# Example
public static class Logger
{
private static log4net.ILog Log { get; set; }
static Type obtype;
static Logger()
{
Log = log4net.LogManager.GetLogger(typeof(Logger));
}
public static void Error(object msg)
{
Log.Error(msg);
}
public static void Error(object msg, Exception ex)
{
Log.Error(msg, ex);
}
public static void Error(Exception ex)
{
Log.Error(ex.Message, ex);
}
public static void Info(object msg)
{
Log.Info(msg);
}
}
Summary
Here in the above of this blog, we discussed the each steps How to use log4net in C#. This guide line will help you to implement log4net in any application which support C# language. I hope you have enjoued it a lot.
Related Articles
- How to use log4net in C# Console Application
- log4net ASP NET MVC Example
- log4net Configuration for Multiple Files
- How to use log4net in WPF
Thanks