【问题标题】:How to handle deprecation of IWebHostBuilder.UseSerilog() when IWebHostBuilder is still needed?当仍然需要 IWebHostBuilder 时,如何处理 IWebHostBuilder.UseSerilog() 的弃用?
【发布时间】:2022-04-06 22:35:55
【问题描述】:

对于 serilog-aspnetcore 版本 5.0.0 中的 IWebHostBuilder,不推荐使用 UseSerilog() 扩展*。但是我仍在使用 IWebHostBuilder 和 Startup 类(aspnetcore 6),并且不推荐使用 IWebHostBuilder。

由于弃用意味着将来会被移除,我应该如何利用 Serilog 继续前进?


参考: https://github.com/serilog/serilog-aspnetcore/releases/tag/v5.0.0 "在使用 IHostBuilder 的平台上将 IWebHostBuilder 扩展标记为已过时"

【问题讨论】:

标签: serilog


【解决方案1】:

我可以通过切换到 IHostBuilder 而不是 IWebHostBuilder 来实现它。在我的案例中,关键是调用 ConfigureWebHostDefaults(或 ConfigureWebHost),然后您可以在其中使用 IWebHostBuilder。

通过这种方式,我可以在 IHostBuilder 上调用 UseSerilog,同时仍然像以前一样通过 IWebHostBuilder 使用 Startup 类。

例子:

public static void Main(string[] args)
{
    // temp initial logging
    Log.Logger = new LoggerConfiguration()
        .WriteTo.Console()
        .CreateBootstrapLogger();

    using var app =
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webHostBuilder
                => webHostBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                        _ = config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                            .AddJsonFile("appsettings.json", false, true))
                    .UseStartup<Startup>())
            .UseSerilog(
                (hostingContext, loggerConfig) =>
                    loggerConfig
                        .ReadFrom.Configuration(hostingContext.Configuration)
                        .Enrich.FromLogContext(),
                writeToProviders: true)
            .Build();
    app.Run();
}

【讨论】:

    【解决方案2】:

    我解决了:

    var builder = WebApplication.CreateBuilder(args);
    builder.Host.UseSerilog();
    

    【讨论】:

    • 我相信假设您使用的是新的最小托管模型。如前所述,我使用的是 IWebHostBuilder 和 Startup 类,所以这不适用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多