Making log4net .NET Core Work – It’s ALLIIVVEEE!

Matt Watson Live Queue, Uncategorized Leave a Comment

Recently the log4net team published new NuGet packages that support .NETStandard 1.3, which means it should work with .NET Core. I decided to spend some time today to make sure our Stackify logging libraries work with log4net and .NET Core. We already published updates for NLog and Serilog. It was about time we had log4net support out there as well.

Getting Started: Configure() log4net

Adding a reference to the log4net NuGet package was no problem. If you have worked with log4net for any amount of time, you know you have to add the magical line of code for configuring it. Although, you can see from my screenshot below that it doesn’t work like expected.

XmlConfigurator.Configure() requires some parameters that we don’t usually provide in the past.

Configuration Workaround: Loading it Manually

Normally log4net is smart enough to load its configuration from a web.config or log4net.config file. In .NET Core, it doesn’t seem to know how. I searched all over the internet, looked through the log4net repo, downloaded the source, and beat my head on the wall to no avail. 😱

It makes sense that it can’t read from a web.config/app.config because they don’t even exist in .NET Core.

But, it also doesn’t automatically try to read a log4net.config file. As a side note NLog does the same thing. You have to manually configure it now in .NET Core. 🤔

After a little reverse engineering, I figured out how to manually load my log4net.config file and configure log4net.

XmlDocument log4netConfig = new XmlDocument();

using (StreamReader reader = new StreamReader(new FileStream("log4net.config", FileMode.Open, FileAccess.Read)))
{
	log4netConfig.Load(reader);
}

ILoggerRepository rep = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

XmlConfigurator.Configure(rep, log4netConfig["log4net"]);

I was able to get this to work with a .NET Core app targeting both netcoreapp1.0 and net452.

log4net with .NET Core is ALLIIVVEEE!

So after a little trial and error, I was finally able to figure it out. I hope this can be helpful to others who are trying to figure this out. They do list some limitations with the current 2.0.7 version of log4net. Hopefully, we see further improvements to all of this and someone will eventually tell me that my little workaround is silly and there is a better way.

About Matt Watson

Matt is the Founder & CEO of Stackify. When he isn't hacking away on new Stackify product features he is hacking away on new new blog posts like this.