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:
I think I've figured out an acceptable solution, although not exactly the way I asked the question.
First of all, I create a "LoggerFactory", which has a single method called "GetLogger" (which creates the concrete NLog Logger and accepts a class name as a parameter), and I inject this factory instead of the logger directly.
LoggerFactory:
public class LoggerFactory : ILoggerFactory
{
public ILogger GetLogger(string fullyQualifiedClassName)
{
return new NLogLogger(fullyQualifiedClassName);
}
}
NLogLogger:
public class NLogLogger : ILogger, INLogLogger
{
NLog.Logger mylogger;
public NLogLogger(string fullyQualifiedClassName)
{
mylogger = NLog.LogManager.GetLogger(fullyQualifiedClassName);
}
}
Startup.cs:
services.AddScoped<BLL.Logging.ILoggerFactory>();
The in my controller class, I've got:
private BLL.Logging.ILogger logger;//my NLogLogger inherits this interface
public HomeController(BLL.Logging.ILoggerFactory loggerFactory)
{
logger = loggerFactory.GetLogger(this.GetType().FullName);
}
So what I've effectively now done, is rather than injecting the actual Logger itself (Which @Steven indicated would not be possible the way I was trying to do it), I've instead injected the utility to create an instance of a logger which wraps NLog.
I've still got the responsibility to create the logger within the class, but at least I've decoupled from the underlying logging framework (NLog).
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: