I've got a .NET Core web app that I'm trying to add logging to via NLog. In previous projects, I've just used something like the following at the top of every class:
private static Logger logger = LogManager.GetCurrentClassLogger();
I'm trying to follow more best practices with this project where possible.
My question is, how can I inject a logger which has the fully qualified name of the class that it's being injected into?
In my startup.cs file, so far I've got the following:
services.AddScoped<BLL.Logging.NLogLogger>();
At the moment, the NLogLogger
class creates an instance of an NLog Logger via GetCurrentClassLogger()
, which when used will only ever report the name as "BLL.Logging.NLogLogger" rather than the actual class that the logger is being injected into.
To simplify the question and make it a bit more generic: How can you pass in the name of the class that .NET Core is going to inject a class into?
I've thought about something like the below, but not sure how to achieve it:
services.AddScoped<BLL.Logging.NLogLogger>(serviceProvider => new BLL.Logging.NLogLogger("class name here"));
Using DI specify ILogger<T>
type instead of Logger
, where T
is the class type that uses the logger, so NLog will know about the class. For example:
public class TodoController : Controller
{
private readonly ILogger _logger;
public TodoController(ILogger<TodoController> logger)
{
_logger = logger;
}
}
References: