Most things are easy when you know how to do it. I found little information and nothing complete on how to get Log4Net working in .Net Core 2.0.
This will be a short description covering the steps needed to get it up and running.
First create a new project from Visual Studio. I use Visual Studio 2017. For simplicity I selected to create a console application.
A basic console application doesn’t need much code. Visual Studio has already created a class called Program with a Main method for you.
Just create an instance of the Program class and call a method named Run. Also create methods Run and LogDemo like this
[code language=”csharp”]
static void Main(string[] args)
{
Program program = new Program();
program.Run();
}
private void Run()
{
Console.WriteLine(”Logging demo”);
LogDemo();
Console.WriteLine(”\nPress any key to continue …”);
Console.ReadKey();
}
private void LogDemo()
{
}
[/code]
We need to use two extension packages from Microsoft; dependency injection and Log4Net.
Install them using the Package Manager (found in the Tools menu; NuGet Package Manager->Package Manager Console) like this:
[code]
Install-Package Microsoft.Extensions.DependencyInjection
Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore
[/code]
To be able to use these in our code, we have to add two ”usings”
[code language=”csharp”]
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
[/code]
In order to easily change the log4net settings add a config-file called log4net.config to the project.
My file looks like this and will log to a file in c:\temp called demo.log as well as to the console.
[code]
<?xml version=”1.0″ encoding=”utf-8″ ?>
<log4net>
<appender name=”RollingLogFileAppender” type=”log4net.Appender.RollingFileAppender”>
<lockingModel type=”log4net.Appender.FileAppender+MinimalLock”/>
<file value=”c:\temp\demo.log” />
<staticLogFileName value=”true”/>
<appendToFile value=”true”/>
<rollingStyle value=”Date”/>
<maxSizeRollBackups value=”100″/>
<maximumFileSize value=”10MB”/>
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%date %level %logger – %message%newline” />
</layout>
</appender>
<appender name=”console” type=”log4net.Appender.ConsoleAppender”>
<layout type=”log4net.Layout.PatternLayout”>
<conversionPattern value=”%message%newline” />
</layout>
</appender>
<root>
<level value=”All”/>
<appender-ref ref=”RollingLogFileAppender”/>
<appender-ref ref=”console” />
</root>
</log4net>
[/code]
If you experience problems where the application can’t find your config-file, try changing the file property ”Copy to Output Directory” to ”Copy if newer” or ”Copy always”.
Now add a logger member to the Program class
[code language=”csharp”]
private ILogger logger;
[/code]
Then add a constructor to the Program class
[code language=”csharp”]
public Program()
{
ServiceProvider serviceProvider = new ServiceCollection()
.AddLogging(logBuilder => logBuilder.SetMinimumLevel(LogLevel.Debug))
.AddSingleton<ILogger>(log =>
{
return new LoggerFactory()
.AddLog4Net().
CreateLogger(”Demo”);
})
.BuildServiceProvider();
logger = serviceProvider.GetService<ILogger>();
}
[/code]
It’s important to set the minimum level for logging, otherwise the level set in log4net.config is not working if set to a lower value. This took quite some time to figure out.
Finally, add some logging to the LogDemo method.
[code language=”csharp”]
private void LogDemo()
{
logger.LogInformation(”Application started.”);
logger.LogCritical(”Demo critical”);
logger.LogDebug(”Demo debug”);
logger.LogError(”Demo error”);
logger.LogTrace(”Demo trace”);
logger.LogWarning(”Demo warning”);
}
[/code]
That should be it! Run the program.