1

I need to write to various log files for different errors in the same file.

This is simple in .net 4 as I just call LogManager.GetLogger("logname"). So I could target a specific logger.

However in .net core I only have the injected ILogger<MyClass> and it writes to all the loggers.

How do I target a specific logger in .net core?

coolblue2000
  • 3,796
  • 10
  • 41
  • 62
  • are looking for something like this?: https://stackoverflow.com/questions/28913502/is-it-possible-to-tell-dynamically-nlog-which-target-to-log-to – crizcl Feb 24 '21 at 13:47
  • I think you're looking for this: https://stackoverflow.com/a/65748371/201303 – Julian Feb 24 '21 at 15:19

1 Answers1

0

The Microsoft Extension Logging (MEL) uses the generic ILogger<T>, as a trick to create ILogger imbued with the type-name.

But instead of doing this:

public class MyClass
{
  private readonly ILogger _logger;   // Notice no generic

  public MyClass(ILogger<MyClass> logger) 
  {
    _logger = logger;
    _logger.LogInformation("Hello");
  }
}

Then one can ask the Microsoft Dependency Injection to provide the ILoggerFactory as constuctor parameter:

public class MyClass
{
  private readonly ILogger _logger;   // Notice no generic

  public MyClass(ILoggerFactory loggerFactory) 
  {
    _logger = loggerFactory.CreateLogger(GetType().ToString());  // Performance hit
    _logger.LogInformation("Hello");

    var otherLogger = loggerFactory.CreateLogger("LogName"); // Same as LogManager.GetLogger("logname")
    otherLogger.LogInformation("Hello Again");
  }
}
Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70