Serilog:登录到不同的文件

时间:2016-07-20 12:23:56

标签: c# serilog

我将所有类型的事件记录到单个Json文件中,而不管LogLevel。现在我需要将一些自定义性能计数器记录到单独的Json文件中。怎么能在Serilog做到这一点。我应该创建不同的Logger实例并使用它来记录性能计数器吗?想与LibLog一起使用

3 个答案:

答案 0 :(得分:11)

您可以首先确保使用特定属性值(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();

答案 1 :(得分: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"
    }
  }
}

然后,您只需要修改CreateHostBuilder文件中的Program.cs方法即可从配置文件中读取该方法

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

有关更多详细信息,请参阅帖子here

答案 2 :(得分:1)

如果您想拥有一个独立的日志记录管道,只需创建另一个实例。 这是从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
}