Introduction
Nowadays, most applications use logging as a way to store information about performed operations, because those data are very useful when you have to diagnose issues while running your apps. We have many ways to store the log into database, textfile, etc. Instead of using complex ways, go ahead to use an easier to use and existing open source library such as log4net. It's a common library, very powerful and the most important is very easy to use.
Should Know Before Starting
- Application demo: Console app
- Log4Net version: 2.0.5
- Visual Studio: 2015
There are 5 log message levels:
FATAL
ERROR
WARN
INFO
DEBUG
You will also be able to find the video link here: Perfect Log4Net with C#
Integration Steps
Follows the steps to do the integration between Log4Net and C# Console application as example:
Step 1
Open your Visual Studio instance on your PC.
Step 2
Create a console project.
Step 3
Add log4net
refer to your project. We have 2 ways for adding that library. The first one is download the log4net from the internet to your local device, then add the reference to DLL file. The second one is download it from Nuget. I preferred this way by the following:
- Right clicks on your project
- Click Manage NuGet Packages…
- Clicks on Browse on the left hand
- Type log4net in search box under Browse option
- Select log4net package and click Install
Step 4
Open AssemblyInfo.cs file under Properties, then add the below line of code under the [assembly: AssemblyCulture("")]
line.
// Let log4net know that it can look for configuration in the default application config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Step 5
Open the App.config
file, by default after creating the console app, it will contain the following code:
="1.0" ="utf-8"
<configuration>
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
Next, add the configuration code for log4net into this file, but don't forget to add those configurations before <startup> </startup>
tag to make sure the log4net runs well. After that, it should be:
="1.0" ="utf-8"
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<appender name="TestAppender"
type="log4net.Appender.RollingFileAppender" >
<file value="E:\log\MyTestAppender.log" />
<encoding value="utf-8" />
<appendToFile value="true" />
<rollingStyle value="Date" />
-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level [%thread] %type.%method - %message%n" />
</layout>
</appender>
<root>
<level value="All" />
-->
<appender-ref ref="TestAppender" />
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
I'm going to explain a little for the above configured.
This line of code...
<configSections> <section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections>
...lets the log4net know that the real configuration is stored in XML node called log4net
, where we can setup the output log file, define the output layout for messages and set the roolingstyle for data file, etc.
Step 6
Open the Program.cs
file, by default, it contains only the Main(string[] args)
method. Go ahead to create a method called ImplementLoggingFuntion
, which implements the logging feature using log4net. The full code for Program.cs is as below:
using System;
using log4net;
using System.Threading;
namespace Log4Net.CSharp
{
class Program
{
private static readonly ILog Log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
ImplementLoggingFuntion();
}
private static void ImplementLoggingFuntion()
{
var secs = 3;
Log.Fatal("Start log FATAL...");
Console.WriteLine("Start log FATAL...");
Thread.Sleep(TimeSpan.FromSeconds(secs));
Log.Error("Start log ERROR...");
Console.WriteLine("Start log ERROR...");
Thread.Sleep(TimeSpan.FromSeconds(secs));
Log.Warn("Start log WARN...");
Console.WriteLine("Start log WARN...");
Thread.Sleep(TimeSpan.FromSeconds(secs));
Log.Info("Start log INFO...");
Console.WriteLine("Start log INFO...");
Thread.Sleep(TimeSpan.FromSeconds(secs));
Log.Debug("Start log DEBUG...");
Console.WriteLine("Start log DEBUG...");
Thread.Sleep(TimeSpan.FromSeconds(secs));
Console.WriteLine("Press any key to close the application");
Console.ReadKey();
}
}
}
Points of Interest
- You can reuse this code for your working purposes
- Very basic, demonstrates and easy to understand
History
- 21-June-2016: Initial version