How to configure ILoggerFactory in .NET 6

2.8k views Asked by At

In .NET 5 Startup.cs class there is Configure method which it's inside ILoggerFactory interface is injected. See below:

     public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            loggerFactory.AddFile("Logs/mylog-{Date}.txt");

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            
            ..........

        }

In .NET 6 how can I get the ILoggerFactory after the var app = builder.Build(); and call its AddFile() method to write logs like .NET 5 above.

4

There are 4 answers

0
Ramin Quliyev On BEST ANSWER

You can do this like that:

using (var scope = app.Services.CreateScope())
{
   
 var loggerFactory = scope.ServiceProvider.GetRequiredService(typeof(ILoggerFactory));
    loggerFactory.AddFile("Logs/mylog-{Date}.txt");

}
0
Divyanshu Kareer On
  • In .Net 5, the Configure method inside Startup.cs is called after Service Provider is built. That is why the dependencies for the method are automatically resolved.
  • In .Net 6, you need to add this code after the service provider is build as part of WebApplicationBuilder's build process.

Something like this:

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
   var loggerFactory = scope.ServiceProvider.GetRequiredService<ILoggerFactory>();

   loggerFactory.AddFile("Logs/mylog-{Date}.txt");
}
0
EylM On

In your Program.cs file, add the following code:

var builder = WebApplication.CreateBuilder(args);

// some initialization.
// example:
builder.Services.AddControllers().AddNewtonsoftJson();

// add logging
builder.Services.AddLogging(logging =>
{
    logging.ClearProviders(); // optional (clear providers already added)
    logging.AddFile("Logs/mylog-{Date}.txt")
});
0
Zohidbek Mengliboyev On

Optimal Answer

After installing Serilog.Extensions.Logging.File nuget package, writing below code:

app.Services.GetRequiredService<ILoggerFactory>().AddFile("Logs/mylog-{Date}.txt");