在配置准备就绪之前配置Serilog?

发布于 2025-02-03 13:23:45 字数 1190 浏览 6 评论 0 原文

我有一个Web API(.NET Core 3.1),它使用Serilog进行记录。很早地将Serilog添加到 iwebhostbuilder

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    return WebHost
        .CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseSerilog((context, configuration) =>
        {
            if (context.HostingEnvironment.IsDevelopment())
            {
                configuration.WriteTo.Console(LogEventLevel.Debug);
                return;
            }

            configuration.WriteTo.ApplicationInsights(TelemetryConverter.Traces, LogEventLevel.Error);
        });
}

这意味着(AFAIK)我此时已经配置了该记录器。因此,这是我主要要做的第一件事:

public static int Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .CreateLogger();

    var host = CreateWebHostBuilder(args).Build();
    host.Run();
}

但是行 .readfrom.configuration(配置)需要设置配置。这通常是在 startup (再次是AFAIK)中完成的,此时尚未运行。显然,我可以将我的 loggerConfiguration 移至以后,但是在配置之前, .isserilog 将调用。

那么,当我尚未设置时,如何使用 iconfugration 配置Serilog?

I have a web api (.NET Core 3.1) which is using Serilog for logging. Serilog is added to the IWebHostBuilder quite early:

public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
    return WebHost
        .CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseSerilog((context, configuration) =>
        {
            if (context.HostingEnvironment.IsDevelopment())
            {
                configuration.WriteTo.Console(LogEventLevel.Debug);
                return;
            }

            configuration.WriteTo.ApplicationInsights(TelemetryConverter.Traces, LogEventLevel.Error);
        });
}

This means (afaik) that I need to have already configured the logger at this point. So this is the very first thing I do in the main:

public static int Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(Configuration)
        .CreateLogger();

    var host = CreateWebHostBuilder(args).Build();
    host.Run();
}

But the line .ReadFrom.Configuration(Configuration) requires the configuration to be set up. This is usually done in the StartUp (again, afaik) which has not yet been run at this time. Obviously I could move my LoggerConfiguration to later, but the .UseSerilog would be called before it was configured.

So how do I configure Serilog with IConfugration, when I haven't set it up yet?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吾家有女初长成 2025-02-10 13:23:45

@rubenbartelink指出了一个很好的评论。

这在

特别是两阶段初始化部分,该部分指出:

两个阶段初始化

此页面顶部的示例显示了应用程序启动时如何立即配置Serilog。

这具有在ASP.NET核心主机设置期间捕获和报告例外的好处。

首先初始化Serilog的缺点是arsp.net核心主机的服务,包括 appSettings.json 配置和依赖项注入。

为了解决这个问题,Serilog支持两个阶段的初始化。当程序启动时,立即将立即配置一个初始的“ Bootstrap”记录器,一旦主机加载,它将被完全配置的记录器替换。
要使用此技术,请首先用 create bootstraplogger()

替换初始 createLogger()调用

 

然后,将回调传递到 useserIlog()创建最终记录器:

  public static iHostBuilder create-hostbuilder(string [] args)=&gt;
    host.CreatedEdeFaultBuilder(args)
        .ISSERILOG((上下文,服务,配置)=&gt;配置
            。
            .Readfrom.Services(服务)
            .enrich.fromlogcontext()
            .writeto.console())
        。
        {
            webbuilder.usestartup&lt; startup&gt;();
        });
 

重要的是要注意,最终记录器完全替换了引导程序记录器:如果您要两者都登录到控制台,则需要在这两个中指定 writeto.console()如示例所示的位置。

消费 appsettings.json 配置

使用两个阶段初始化,插入 readfrom.configuration(context.configuration)上面示例中显示的调用。 JSON配置语法记录在Serilog.settings.configuration readme中。

@RubenBartelink pointed to a very good ressource in comment.

This is also described in the Serilog for ASP.NET Core documentation.

In particular the two-stage initialization part, which states:

Two-stage initialization

The example at the top of this page shows how to configure Serilog immediately when the application starts.

This has the benefit of catching and reporting exceptions thrown during set-up of the ASP.NET Core host.

The downside of initializing Serilog first is that services from the ASP.NET Core host, including the appsettings.json configuration and dependency injection, aren't available yet.

To address this, Serilog supports two-stage initialization. An initial "bootstrap" logger is configured immediately when the program starts, and this is replaced by the fully-configured logger once the host has loaded.
To use this technique, first replace the initial CreateLogger() call with CreateBootstrapLogger():

using Serilog;
using Serilog.Events;

public class Program
{
    public static int Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateBootstrapLogger(); // <-- Change this line!

Then, pass a callback to UseSerilog() that creates the final logger:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog((context, services, configuration) => configuration
            .ReadFrom.Configuration(context.Configuration)
            .ReadFrom.Services(services)
            .Enrich.FromLogContext()
            .WriteTo.Console())
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

It's important to note that the final logger completely replaces the bootstrap logger: if you want both to log to the console, for instance, you'll need to specify WriteTo.Console() in both places, as the example shows.

Consuming appsettings.json configuration

Using two-stage initialization, insert the ReadFrom.Configuration(context.Configuration) call shown in the example above. The JSON configuration syntax is documented in the Serilog.Settings.Configuration README.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文