Logging frameworks that allows you to easy to write your logs to different places by simply changing your configuration. You can write your .NET logs to a file on disk, a database, a log management system or potentially dozens of other places, all without changing your code.
Installing
Run this quick command from the Package Manager Console.
PM> Install-Package log4net
After running the install, you should get a “log4net” in the references section.
App.config
Add the following to your App.confi file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config. Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:/Logs/Test.log"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="3000"/>
<maximumFileSize value="10000KB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
</configuration>
AssemblyInfo.cs
Add the following to your AssemblyInfo.cs file.
[assembly: log4net.Config.XmlConfigurator()]
Code
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsoleApp01
{
public class TestTask
{
private static readonly ILog log = LogManager.GetLogger(typeof(TestTask));
public static void Main(string[] args)
{
log.Info("TestTask started");
}
}
}
A log file should be generated in the folder you set in the App.config.
Make Good Use of Multiple Log Levels and Filter by Them
Be sure to use Debug, Info, Warning, Error, and Fatal logging levels as appropriate within your code. Don’t lot everything as Debug. Be sure to think about how you would be viewing the logs and what you want to see it later when coding your logging statements.
You can specify in your log4net config which log4net logging levels you want to log. This is really valuable if you want to specify only certain levels to be logged to a specific log appender or to reduce logging in production. This also you to log more or less data without changing your code.
log4net levels:
- All – Log everything
- Debug
- Info
- Warn
- Error
- Fatal
- Off – Don’t log anything
Sources:
Comments