11

In .Net5 ILoggerFactory is used as Configure function in Startup.cs as follows :

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    //here we used loggerFactory
    loggerFactory.AddProvider(loggerprovider);
}

In .Net6 how to get it with aap or builder

var app = builder.Build();

OR

var builder = WebApplication.CreateBuilder(args);
Faraz Ahmed
  • 1,467
  • 2
  • 18
  • 33
  • Use `services.AddLogging()` in your `ConfigureServices` method - https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.loggingservicecollectionextensions.addlogging – Dai Nov 12 '21 at 05:25
  • @Dai I need ILoggerFactory instance for adding provider like loggerFactory.AddProvider( – Faraz Ahmed Nov 12 '21 at 05:33

4 Answers4

7

WebApplicationBuilder exposes Logging property which has AddProvider(ILoggingBuilder, ILoggerProvider) extension method available. Try using it:

builder.Logging.AddProvider(loggerprovider);
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
6

To get the actual logger factory instance:

var app = builder.Build();
var lf = app.Services.GetRequiredService<ILoggerFactory>();

One could also use GetService rather than GetRequiredService. When the service does not exist, GetService returns null and GetRequiredService throws an exception. Pros and cons discussed here:

https://andrewlock.net/the-difference-between-getservice-and-getrquiredservice-in-asp-net-core/

John Goudy
  • 181
  • 3
  • 7
2

You can Get ILoggerFactory in dotnet 6 by GetService method in Program.cs class, after builder.Build()

var loggerFactory = app.Services.GetService<ILoggerFactory>();
1

Applies to .net 6 web api | Program.cs

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Log4Net.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.AddLog4Net();

Above worked for me in .net 6

  1. Check the log file in : \bin\Debug\net6.0 (detail message)
  2. Also in event viewer -> Windows logs -> Application (general exception)

Thanks to: https://onloupe.com/blog/does-log4net-work-on-net6/

Anish Kutti
  • 337
  • 2
  • 7