【问题标题】:Serilog Multiple Sinks Not WorkingSerilog 多个接收器不工作
【发布时间】:2015-03-10 16:17:08
【问题描述】:

我正在使用 serilog 将所有 Web API 跟踪事件记录到一个文件中,并通过以下代码将所有代码调试到另一个文件:

问题是 trace.json 也在记录调试事件,我怀疑这是因为 minimumLevel 过滤器。

如何将事件分成两个文件?

尝试this 问题,但它根本不写入文件。

使用最新的 serilog 版本。

Log.Logger = new LoggerConfiguration()
.WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({HttpRequestId}|{UserName}) {Message}{NewLine}{Exception}")
.MinimumLevel.Debug()
.WriteTo.Sink(new FileSink(@"E:\log.json", new JsonFormatter(false, null, true), null), LogEventLevel.Debug)
.MinimumLevel.Verbose()
.WriteTo.Sink(new FileSink(@"E:\trace.json", new JsonFormatter(false, null, true), null), LogEventLevel.Verbose)
.Enrich.With<HttpRequestIdEnricher>()
.Enrich.With<UserNameEnricher>()
.Enrich.WithProperty("App", "CarbonFactoryERP")
.CreateLogger();

以下是我如何称呼记录器:

Log.Logger.Debug("Web API Register Method started at {TimeStamp}",DateTime.UtcNow);

Log.Logger.Verbose("{TimeStamp} {Operation} {Operator} {Message} {Category}", rec.Timestamp, rec.Operation, rec.Operator, rec.Message, rec.Category);

【问题讨论】:

    标签: asp.net-mvc logging asp.net-web-api serilog


    【解决方案1】:

    这是 Serilog 接收器的预期行为。最低级别参数仅指定最小值,正如您所期望的那样 - 不是完全匹配的级别。

    要解决这个问题并仅将特定级别写入接收器,您可以创建一个单独的日志管道并应用限制并使用它:

    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Verbose()
        .WriteTo.Logger(config => config
            .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
            .WriteTo.Sink(new FileSink(@"E:\trace.json", ...))
        // Write to other sinks here
    

    (可能需要一些错字更正,凭记忆进行。)

    【讨论】:

    • 正如问题中已经提到的,我试过这个,当我使用过滤器时,日志文件根本没有被写入。我又试了一次,还是一样。
    • 我决定使用多个顶级记录器,直到我得到这个工作。
    【解决方案2】:

    此示例将根据日志级别和 SourceContext(应用程序命名空间、类名等)将日志记录到同一个接收器(但可以写入不同的接收器)。它对 MyAppRootNamespace 的所有类都有一个详细的最小日志级别,对其他源上下文(Microsoft.* 等)有一个警告最小日志级别。这将为您提供确切需求的起点。

    Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .Enrich.FromLogContext()
                    .WriteTo.Logger(lc => lc
                        .Filter.ByIncludingOnly(Matching.FromSource("MyAppRootNamespace"))
                        .WriteTo.Seq("http://localhost:1009"))
                    .WriteTo.Logger(lc => lc
                        .Filter.ByIncludingOnly(e => e.Level >= LogEventLevel.Warning)
                        .Filter.ByExcluding(Matching.FromSource("MyAppRootNamespace"))
                        .WriteTo.Seq("http://localhost:1009"))
                    .CreateLogger();
    

    要使源上下文 (MyAppRootNamespace) 正常工作,您需要为每个要登录的类添加一个 vble。

    public class MyClass
    {
        private ILogger _log = Log.ForContext<MyClass>();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      相关资源
      最近更新 更多