I have a .Net 6 Web API project with NLog configured following the steps at Getting started with ASP.NET Core 6. I'd like to move NLog references to it's own Class Library. I was following an article on ASP.NET Core Web API – Logging With NLog. The problem is that this method requires me to change all my controllers from
private readonly ILogger<MyController> _logger;
public MyController(ILogger<MyController> logger) {...}
to
private readonly ILoggerManager _logger;
public MyController(ILoggerManager logger) {...}
Is there a way to get NLog in it's own Class Library, yet keep the current syntax that was built-in to the API?
Here's my current program.cs file:
using NLog;
var logger = LogManager
.LoadConfiguration(string.Concat(Directory.GetCurrentDirectory(), "/Configs/NLog/nlog.config"))
.Setup()
.SetupExtensions(x => x.RegisterLayoutRenderer<BuildConfigLayoutRenderer>("BuildConfiguration"))
.GetCurrentClassLogger();
logger.Debug("init main");
try {
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// NLog: Setup NLog for Dependency injection
/********************************************
the 2 lines below are:
1) the default taken from NLog docs and
2) the code from the article I was following (currently disabled)
********************************************/
builder.Host.UseNLog(); // 1
//builder.ConfigureLoggerService(); // 2
/********************************************/
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
} catch (Exception exception) {
logger.Error(exception, "Stopped program because of exception");
throw;
} finally {
LogManager.Shutdown();
}