Reputation: 614
I am using NLog as logging provider in my solution, but some projects have migrated to Microsoft.Extensions.Logging. We're still evaluating if migrating also the rest of the code to this, but in the meantime we need somehow to convert our NLog.ILogger
instance to Microsoft.Extensions.Logging.ILogger<T>
instance.
I know it can be quite easily done using NLog.Extensions.Logging package, adding NLog as provider:
ILoggerFactory factory = LoggerFactory.Create(builder =>
{
builder.AddNLog();
});
return factory.CreateLogger<MyClass>();
but this approach actually creates an NLog provider using the static NLog stuff, not the NLog.ILogger
instance I receive from other code parts.
So, is there a way to use this NLog.ILogger
instance in this conversion? Am I missing something?
Upvotes: 6
Views: 4257
Reputation: 19847
Unless you are using isolated NLog LogFactory-instances, then you can always just do this:
AddLogging(new NLog.Extensions.Logging.NLogLoggerFactory());
And you can also store the NLogLoggerFactory
as static singleton, so you can reuse it everywhere, until everyone have converted to dependency-injection.
But if you want to make it pretty (and it sounds like it will never be), then sadly enough the NLog ILogger has a reference to NLog LogFactory, so you can do this:
NLog.ILogger nlogLogger = NLog.LogManager.GetCurrentClassLogger();
var nlogProvider = new NLog.Extensions.Logging.NLogLoggerProvider(new NLogProviderOptions(), nlogLogger.Factory);
var nlogFactory = new NLog.Extensions.Logging.NLogLoggerFactory(nlogProvider);
Microsoft.Extensions.Logging.ILogger ilogger = nlogFactory.CreateLogger<MyClass>();
Upvotes: 4
Reputation: 5805
The accepted answer did not work for me. I noticed that builder.AddNLog
accepts a LoggingConfiguration
argument and my NLog.ILogger
can expose its configuration!
Looks like this:
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
...
using (ILoggerFactory factory = LoggerFactory.Create(builder =>
builder.AddNLog(Logger.Factory.Configuration))
)
{
return factory.CreateLogger<MyClass>();
}
...
Upvotes: 3