如何配置 Serilog sink wrapper 和 wrapped sinks

How to configure Serilog sink wrapper and wrapped sinks

C. Augusto Proiete's answer to , the code below works, but what is the recommended way to move this configuration to a configuration file. Keeping Serilog.Settings.Xml 是我们的首选,但我们会考虑其他选项。

另外,写入两个接收器有问题吗?还是已经解决了?

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Xml(serilogXmlFilePath)
    .WriteTo.LogLevelModifierSink(writeTo => {
        writeTo.File(
            outputTemplate: "{Timestamp:HH:mm:ss.fff} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}{NewLine}{ThreadId}",
            path: @"C:\inetpub\logs\serilog.txt",
            rollingInterval: RollingInterval.Day,
            shared: true);
        writeTo.Seq("http://localhost/seq/");
    })
    .CreateLogger();

Serilog 配置扩展如 Serilog.Settings.Xml, Serilog.Settings.Configuration 等都以相同的方式工作:它们尝试找到与配置中的接收器名称和参数相匹配的扩展方法.

即当你做这样的事情时:

<?xml version="1.0" encoding="utf-8" ?>
<serilog>
  <using>
    <add name="Serilog.Sinks.File" />
  </using>
  
  <writeTo>
    <sink name="File">
      <arg name="path" value="log.txt" />
    </sink>
  </writeTo>
</serilog>

Serilog 配置扩展尝试 运行 如下所示的方法:

public static LoggerConfiguration File(
    this LoggerSinkConfiguration loggerSinkConfiguration, string path)
{
   // ...
}

在这个例子中,就是Serilog.Sinks.File提供的方法。

在您的情况下,假设您要创建自定义接收器,您还必须提供自定义扩展方法,该方法可以接收配置接收器所需的所有参数,然后设置因此。所以它看起来像这样:

<?xml version="1.0" encoding="utf-8" ?>
<serilog>

  <using>
    <add name="Namespace.Where.Your.Extension.Method.Is" />
  </using>

  <writeTo>
    <sink name="LogLevelModifier">
      <arg name="filePath" value="C:\inetpub\logs\serilog.txt" />
      <arg name="seqUrl" value="http://localhost/seq/" />
    </sink>
  </writeTo>

</serilog>

// Extension method to hook the wrapper into the configuration extension
public static class LoggerSinkConfigurationLogLevelModifierExtensions
{
    public static LoggerConfiguration LogLevelModifier(
        this LoggerSinkConfiguration loggerSinkConfiguration,
        string filePath = null,
        string seqUrl = null)
    {
        return LoggerSinkConfiguration.Wrap(loggerSinkConfiguration, sink =>
            new LogLevelModifierSink(sink), writeTo =>
            {
                if (!string.IsNullOrWhiteSpace(filePath))
                {
                    writeTo.File(filePath);
                }
                
                if (!string.IsNullOrWhiteSpace(seqUrl))
                {
                    writeTo.Seq(seqUrl);
                }

                // etc.

            }, LevelAlias.Minimum, null);
    }
}