huorswords / Microsoft.Extensions.Logging.Log4Net.AspNetCore

Allows to configure Log4net as Microsoft Extensions Logging handler on any ASP.NET Core application. Original code proposal by @anuraj --> https://dotnetthoughts.net/how-to-use-log4net-with-aspnetcore-for-logging/
Apache License 2.0
248 stars 122 forks source link

Logging to different Log4Net loggers with dependency injection #124

Open tiofred opened 2 years ago

tiofred commented 2 years ago

Hello. I achieved this : Using dependency injection, I managed to load log4net confile and to pass ILogger<> to constructors. It works fine with a root logger and multiple appenders filtering the level, so i.e. it logs DEBUG to a file and ERROR to another. .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); logging.AddLog4Net("config.log4Net.xml", true); `<?xml version="1.0" encoding="utf-8" ?>

` What I'd like is : Configure in log4net two loggers, one for the on-the-fly infos, one for the on-the-fly datas. But also being able to inject those two loggers in my constructors to be able to log inside MyServiceAppender or DataAppender using the DEBUG level. `myServiceLogger.LogDebug("test");` goes to Infos.log `myDataLogger.LogDebug("test");` goes to Data.log Is there any way to achieve this ? Thanks for the help.
tiofred commented 2 years ago

I found a way to achieve this, with dependency injection. I write it here, it might be useful for someone else : I replaced in the constructor's prototype ILogger<AcquisitionManager> myLogger by ILoggerFactory loggerFactory and added ILogger myServiceLogger = loggerFactory.CreateLogger("MyService"); ILogger myDataLogger = loggerFactory.CreateLogger("DataService");

I leave it open for now, if you think that's the right way it should be closed. If there's another way, I'd be glad to hear about it.