Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection wth NLog

Tags:

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"));
like image 618
Steviebob Avatar asked Jan 08 '17 15:01

Steviebob


People also ask

Can we use dependency injection in .NET framework?

.NET supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. Dependency injection in .NET is a built-in part of the framework, along with configuration, logging, and the options pattern.

How do you integrate NLog?

Adding NLog NuGet Package As a first step we need to install NLog from NuGet package manager. To do this, right click the Project from Solution Explorer and select Manage NuGet Packages from the context menu. It will open the Package Manager Solution window. From the Package Manager window, browse for NLog.


1 Answers

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:

  • Getting started with ASP.NET Core (csproj vs2017)
  • Getting started with ASP.NET Core 2
  • Getting started with ASP.NET Core 3
like image 120
Set Avatar answered Oct 20 '22 05:10

Set