Search code examples
c#asp.net-core.net-coreasp.net-web-apinlog

How to inject NLog in DI in ASP.NET Core 6 Web API application


I have multiple projects and I want to add NLog to all my projects so I created one common project and I want to use it as a nuget package in other projects.

I am configuring NLog programmatically. I want to inject my package class in the dependency pool as Singleton.

Here is my common package class:

public class CustomConfiguration
{
    public LoggingConfiguration ConfigureLogger(bool fileLogging = false)
    {
        var config = new LoggingConfiguration();

        if (enableFileLogging)
        {
            var fileTarget = new FileTarget("fileTarget");
            fileTarget.FileName = "logs/log.txt";
            fileTarget.Layout = "${longdate} ${level:uppercase=true} - ${message}";
            config.AddTarget("file", fileTarget);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget);
        }

        return config;
    }
}

In my program.cs file I am doing like below but it's not working:

var builder = WebApplication.CreateBuilder(args);

var logger = NLog.LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
builder.Logging.Services.AddSingleton<CustomConfiguration>();
builder.Logging.ClearProviders();
builder.Host.UseNLog();

logger.Info("Service Init");

It not picking a setting that I defined on CustomConfiguration.


Solution

  • I suppose you can explicitely tell NLog to use CustomConfiguration.ConfigureLogger before registering NLog like this:

    NLog.LogManager.Configuration = CustomConfiguration.ConfigureLogger();
    // ...
    builder.Host.UseNLog();
    

    Not sure if it's possible to register that configuration for NLog to get it from DI see Configuration in C# section for details (just a reference I found), but if it is, I would assume it should be registered as LoggerConfiguration and inherit from that class.

    Another possible solution to getting configured logger instance before builder.Build() is called (if this is what you need in this example) can be found in this answer.