【问题标题】:Serilog : Log to different filesSerilog:记录到不同的文件
【发布时间】:2016-11-23 16:31:06
【问题描述】:

我将所有类型的事件记录到单个 Json 文件中,而与 LogLevel 无关。现在我需要将一些自定义性能计数器记录到单独的 Json 文件中。这如何在 Serilog 中完成。我应该创建不同的记录器实例并在我要记录性能计数器的地方使用它吗?想在 LibLog 中使用它

【问题讨论】:

标签: c# serilog


【解决方案1】:

您可以通过首先确保使用特定属性值(LibLog 中的OpenMappedContext())或来自特定类型/命名空间来标记性能计数器事件来做到这一点。

var log = LogProvider.For<MyApp.Performance.SomeCounter>()
log.Info(...);

在配置 Serilog 时,应用了过滤器的 sub-logger 可以仅将所需的事件发送到第二个文件。

Log.Logger = new LoggerConfiguration()
    .WriteTo.Logger(lc => lc
        .Filter.ByExcluding(Matching.FromSource("MyApp.Performance"))
        .WriteTo.File("first.json", new JsonFormatter()))
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(Matching.FromSource("MyApp.Performance"))
        .WriteTo.File("second.json", new JsonFormatter()))
    .CreateLogger();

【讨论】:

  • 阅读您的文章:Serilog 2.0 与子记录器的冒险。不确定如果我错过了什么,但是,如果我这样做,来自“MyApp.Performance”的日志也会转到外部记录器,对吗?我不希望将这些特定日志写入主日志文件。跨度>
  • 添加两个带有反向过滤器的子日志管道应该可以做到。更新答案..
  • 这对我有用。编辑答案以删除 JsonFormatter。
  • 你有这个的 json 例子吗?
【解决方案2】:

我们也可以在配置文件中进行设置。下面给出了appsettings.json 中的示例,用于根据级别拆分滚动文件的日志

{
 
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/ex_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      },
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "(@Level = 'Information' or @Level = 'Debug')"
                }
              }
            ],
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/cp_.log",
                  "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }
    ],
    "Enrich": [
      "FromLogContext",
      "WithMachineName"
    ],
    "Properties": {
      "Application": "MultipleLogFilesSample"
    }
  }
}

那么,您只需修改Program.cs文件中的CreateHostBuilder方法,即可从配置文件中读取

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .UseSerilog((hostingContext, loggerConfig) =>
                loggerConfig.ReadFrom.Configuration(hostingContext.Configuration)
            );

更多详情请参考帖子here

【讨论】:

    【解决方案3】:

    如果您想拥有一个独立的日志记录管道,只需创建另一个实例即可。 这是盗用的,改编自https://github.com/serilog/serilog/wiki/Lifecycle-of-Loggers

    using (var performanceCounters = new LoggerConfiguration()
            .WriteTo.File(@"myapp\log.txt")
            .CreateLogger())
    {
        performanceCounters.Information("Performance is really good today ;-)");
    
        // Your app runs, then disposal of `performanceCounters` flushes any buffers
    }
    

    【讨论】:

      【解决方案4】:

      我正在使用以下代码将不同级别记录到不同文件。

      var conn = configuration.GetSection("ConnectionStrings:SqlConn").Value;
      
      var serilogLogger = new LoggerConfiguration()
                  .MinimumLevel.Information()
                  .WriteTo.Console()
                  .WriteTo.MSSqlServer(conn, new MSSqlServerSinkOptions { TableName = "ErrorLogs", AutoCreateSqlTable = true }, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning)
                  .WriteTo.MSSqlServer(conn, new MSSqlServerSinkOptions { TableName = "InfoLogs", AutoCreateSqlTable = true }, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information)
                  .CreateLogger();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 2016-04-22
        • 2022-08-21
        相关资源
        最近更新 更多