在 Net 6 中使用 WebApplicationBuilder 配置 Serilog

Configure Serilog with WebApplicationBuilder in Net 6

我是Net Core 5 我以前用推荐的方法配置Serilog:

public static void Main(string[] args) {

  Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
    
  try {
    Log.Information("Starting up");
    CreateHostBuilder(args).Build().Run();
  }
  catch (Exception ex) {
    Log.Fatal(ex, "Application start-up failed");
  }
  finally {
    Log.CloseAndFlush();
  }

}

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .UseSerilog() 
    .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

如何使用 WebApplicationBuilder 在 Net 6 中配置 Serilog:

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog

var app = builder.Build();

您仍然可以在 Host 上使用相同的扩展方法。

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog();

var app = builder.Build();