Search code examples
c#asp.net.netiloggeriloggerfactory

How to configure ILoggerFactory in .NET 6


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.


Solution

  • 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");
    
    }