Dependency Injection Using NLog

I have a .Net network application that I am trying to add to the log via NLog. In previous projects, I just used something like the following at the beginning of each class:

private static Logger logger = LogManager.GetCurrentClassLogger();

I try, if possible, to follow the best recommendations with this project.

My question is: how can I insert a registrar that has the full name of the class into which it is inserted?

In my startup.cs file so far I have the following:

services.AddScoped<BLL.Logging.NLogLogger>();

Currently, the class NLogLoggercreates an instance of NLog Logger through GetCurrentClassLogger(), which when used will only report the name as "BLL.Logging.NLogLogger", and not the actual class that is the logger injected into.

To simplify the question and make it more universal: How can you pass the class name that .Net Core is going to introduce the class into?

I thought of something like below, but not sure how to achieve it:

services.AddScoped<BLL.Logging.NLogLogger>(serviceProvider => new BLL.Logging.NLogLogger("class name here"));
+4
source share
2 answers

Using DI, specify the type ILogger<T>instead Logger, where Tis the type of the class that the registrar uses, so NLog will know about this class. For instance:

public class TodoController : Controller
{
    private readonly ILogger _logger;

    public TodoController(ILogger<TodoController> logger)
    {
        _logger = logger;
    }
}
+6
source

I think I understood an acceptable solution, although not quite the way I asked the question.

, "LoggerFactory", "GetLogger" ( NLog ), factory logger .

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

:

    private BLL.Logging.ILogger logger;//my NLogLogger inherits this interface

    public HomeController(BLL.Logging.ILoggerFactory loggerFactory)
    {
        logger = loggerFactory.GetLogger(this.GetType().FullName);
    }

, , , Logger ( @Steven , ), , NLog.

, (NLog).

+2

Source: https://habr.com/ru/post/1666153/


All Articles