Convert NLog.ILogger to Microsoft.Extensions.Logging

2.5k views Asked by At

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?

2

There are 2 answers

2
Rolf Kristensen On BEST ANSWER

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 = ??;
var nlogProvider = new NLog.Extensions.Logging.NLogLoggerProvider(nlogLogger.Factory);
var nlogFactory = new NLog.Extensions.Logging.NLogLoggerFactory(nlogProvider);
AddLogging(nlogFactory);
2
HackSlash On

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>();
    }
...