Register NLog as the Microsoft.Extensions.Logging provider for other components

1.6k Views Asked by At

I am writing a .Net Core Console app. I am using NLog, by itself, extensively in my application. (Calling NLog.LogManager.GetCurrentClassLogger() and calling log methods on that.)

I am making use of Entity Framework, which provides a way to control the logs it produces. I'm using the NLogLoggerFactory provided by the NLog.Extensions.Logging project. This is working, and I see appropriate Entity Framework log messages in my log file.

public class MyDataContext : Microsoft.EntityFrameworkCore.DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder builder)
    {
        builder.UseLoggerFactory(new NLog.Extensions.Logging.NLogLoggerFactory());
    }
}

However, I would like to make this change globally, not just for this one use. I want anything that tries to get a logger from Microsoft.Extensions.Logging to get one that writes to the NLog logs.

The instructions I've found so far seem to focus on applications where you've already got a ServiceCollection object, and adding the NLog provider to that. The NLog and MEL tutorial does this as well, creating a ServiceCollection and then retrieving a custom class out of that collection. I don't have a ServiceCollection, so that does nothing for me.

Is there any way to do this registration globally?


Responses to comments:

  • Other question about logging without dependency injection
    • That question was 'how to use the MS Logging Extensions logger', where the answer was 'instantiate your own LoggerFactory to create logger objects', and the asker ended up using NLog in the same way as I'm already using it. I need to affect the default logger factory, whatever things end up resolving if I don't use a ServiceCollection to instantiate them.
  • What is your setup? In general you have a ServiceCollection somewhere
    • I don't have a ServiceCollection, at least not one that I created. For the EFCore DbContext, I create it using its default constructor, using a plain new MyDataContext().
    • If I don't call builder.UseLoggerFactory in OnConfiguring, then it gets a logger from... presumably somewhere, which ends up not writing any messages anywhere, as far as I can see.
    • Wherever the EFCore DbContext gets its default logger from if I don't call UseLoggerFactory, presumably other things are retrieving a logger from there as well, and that is what I want to set, so that more things write to my application logs.
0

There are 0 best solutions below