.Net Core Worker Service cannot find log4net.config when it runs as a windows service

Viewed 1341

I have these projects in my solution:

  1. .Net Core 3.1 Worker Service
  2. .Net Core 3.1 Class library - for configure the log4net

But my log4net.config file is inside my worker service project. When I'm debugging, it is logging to the file which is configured in the log4net.config.

But when I install the Worker Service as a Windows service, it doesn't log to the file.

And when I checked the log4net.config location it has these values:

  1. When debugging: D:\myrepos\webapicore\Development\Message.Consumer\log4net.config
  2. When running as a service: C:\WINDOWS\system32\log4net.config

So I believe, since the log4net.config is not available in C:\WINDOWS\system32\ it cannot do the logging.

UPDATE: I'm using following code to retrieve the log4net.config

var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

Any idea to solve this?

Thanks.

2 Answers

I have installed and configured log4net in a different class library. So when I was getting the Assembly.GetEntryAssembly() it was actually not giving the assembly location of where log4net has been installed.

Therefore I changed the this code part:

var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

Into:

var dirname = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
XmlConfigurator.Configure(new FileInfo(string.Format("{0}{1}", dirname, @"\log4net.config")));

This worked for me.

This worked for me too with my .NET 5 WorkerService.

You could also use AppDomain.CurrentDomain.BaseDirectory, instead.

However, I then found out that you can simply create an AssemblyInfo.cs file (Add new item ...) and add

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Just like before with .NET Framework 4.5, etc.

Related