Home > Software engineering >  .NET Core 6 - How to set ILogger(log4net) for Dependency Injection in Program.cs
.NET Core 6 - How to set ILogger(log4net) for Dependency Injection in Program.cs

Time:02-16

I've moved my new projects to .NET Core 6 but apparently there are radical changes in Program and Startup.cs files.

I would like to use log4net in every Controller with Dependency Injection but I couldn't find any tutorial about Logging in .NET Core 6.

What I tried:

builder.Services.AddLogging();
builder.Logging.AddProvider(loggerProvider);

What should I write to use ILogger in Controllers?

CodePudding user response:

The Logging in ASP.NET Core 6.0 is described in detail in the Microsoft Docs. A very brief summary: You register the logging framework you want to use and then use ASP.NET Core's log layer in the application itself. The translation between the two log systems is done by a handler. For log4net there is a handler on GitHub.

Registration

After you have installed the handler package, you register this handler in the initialization code in Program.cs:

// Add services to the container.
builder.Services.AddControllersWithViews();

// Add your logging handler
builder.Logging.AddLog4Net();

var app = builder.Build();

If you have an old-style template with a separate Startup.cs, you must use the sample code from the project's readme file instead.

Write logs

Now you can get an instance of ILogger in your controllers via the Dependency Injection and log with it. The handler takes care of passing these logs to log4net accordingly.

private readonly ILogger<HomeController> logger;

public HomeController(ILogger<HomeController> logger)
{
    this.logger = logger;
}

public IActionResult Index()
{
    this.logger.LogDebug("Creating /Home/Index");
    return View();
}
  • Related