asp.net 如何在.NET 6中配置ILoggerFactory

pnwntuvh  于 2023-10-21  发布在  .NET
关注(0)|答案(3)|浏览(209)

在.NET 5 Startup.cs类中有一个Configure方法,它在ILoggerFactory接口中注入。见下文:

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();
            
            ..........

        }

在.NET 6中,我如何在 var app = builder.Build(); 并调用它的**AddFile()**方法来像上面的.NET 5那样写入日志。

0mkxixxg

0mkxixxg1#

你可以这样做:

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

}
fsi0uk1n

fsi0uk1n2#

在Program.cs文件中,添加以下代码:

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

sbtkgmzw3#

最佳答案

安装Serilog.Extensions.Logging.File nuget包后,写下面的代码:

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

相关问题