如何创建支持配置逻辑的Serilog Sink Extension

问题描述 投票:1回答:1

我正在尝试包装Serilog.Sinks.Elasticsearch接收器的配置,以便我的日志配置看起来像这样。

    var logger = Log.Logger = new LoggerConfiguration()
          .ReadFrom.AppSettings()
          .Enrich.FromLogContext()
          .Enrich.WithMachineName()
          .Enrich.WithProcessId()
          .Enrich.WithThreadId()
          .WriteTo.ElasticsearchIfEnabled() // <--- Chained Sink
          .WriteTo.Async(
              a => a.File(
                  filePath,
                  outputTemplate: CanonicalTemplate,
                  retainedFileCountLimit: 31,
                  rollingInterval: RollingInterval.Day,
                  rollOnFileSizeLimit: true,
                  buffered: true,
                  flushToDiskInterval: TimeSpan.FromMilliseconds(500)))
        .CreateLogger();

我的灵感来自于这个answer,但我坚持内部条件逻辑,特别是如果接收器被禁用。

这是我到目前为止所拥有的。

public static class MyConfigExtensions
{
    public static LoggerConfiguration ElasticsearchIfEnabled(this LoggerSinkConfiguration loggerSinkConfiguration)
    {
        var isElasticSinkEnabled = GetThisValue();

        if (isElasticSinkEnabled)
        {
            // Code necessary to configure sink....

            return loggerSinkConfiguration.Sink(new ElasticsearchSink(elasticSearchSinkOptions));
        }

        return loggerSinkConfiguration; // <-- what is passed here that will propagate the configuration?
    }
}

所以我的问题是如何在禁用内部接收器时传播配置,我需要将原始配置传递给链中的下一个接收器?

配置对象有一些属性,Logger,Sink和Sink <>但我不确定要使用哪个,更重要的是,正确。

c# serilog
1个回答
1
投票

这将有效:

return loggerSinkConfiguration.Sink(new LoggerConfiguration().CreateLogger());

但是,有条件地配置记录器也是如此:

var configuration = new LoggerConfiguration()
      .ReadFrom.AppSettings()
      .Enrich.FromLogContext()
      .Enrich.WithMachineName()
      .Enrich.WithProcessId()
      .Enrich.WithThreadId();

if (isElasticSinkEnabled)
    configuration.WriteTo.ElasticsearchIfEnabled();

var logger = Log.Logger = configuration.WriteTo.Async(
          a => a.File(
              filePath,
              outputTemplate: CanonicalTemplate,
              retainedFileCountLimit: 31,
              rollingInterval: RollingInterval.Day,
              rollOnFileSizeLimit: true,
              buffered: true,
              flushToDiskInterval: TimeSpan.FromMilliseconds(500)))
    .CreateLogger();
© www.soinside.com 2019 - 2024. All rights reserved.