Serilog Json 配置到 API:过滤器

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

我需要根据名为“EventType”的属性的值记录到不同的接收器。 我在 JSON 配置中找到了一些东西,但我似乎无法理解如何转换为代码(我需要硬编码相同的日志记录策略)。

我阅读了有关 Expressions 的文档,但似乎无法使其工作。

以下是 JSON 配置的摘录:

  "Serilog": {
    "WriteTo": [
      {
        "Name": "Logger",
        "Args": {
          "configureLogger": {
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/SystemLog.txt",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 31,
                  "buffered": false,
                  "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Properties} {Message:lj} {NewLine}{Exception}",
                  "restrictedToMinimumLevel": "Debug"
                }
              }
            ],
            "Filter": [
              {
                "Name": "ByIncludingOnly",
                "Args": {
                  "expression": "EventType = 'System'"
                }
              }
            ],
            "Enrich": [ "FromLogContext" ]
          }
        }
 ]
}

这是我在代码中尝试过的:

loggerConfiguration
    .WriteTo.Logger(configureLogger: conf => {
            conf.WriteTo.File(path: "Logs/SystemLog.txt",
                outputTemplate:
                "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Properties} {Message:lj} {NewLine}{Exception}",
                rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 31,
                buffered: false,
                restrictedToMinimumLevel: LogEventLevel.Debug);
            conf.Filter.ByIncludingOnly( expression: "UserEvent = 'System'");
            conf.Enrich.FromLogContext();
    }); 

我还尝试将过滤器更改为

conf.Filter.ByIncludingOnly( expression: "@p['UserEvent'] = 'System'");

但是仍然没有日志... 如果您能指导我使用正确的语法,我将不胜感激。 谢谢您的帮助。

c# serilog
1个回答
0
投票

我在这里使用控制台应用程序项目模板作为示例,并以.Net7作为目标框架。以下源代码可用这里

程序.cs

using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Debugging;
using Serilog.Events;
using System.Diagnostics;

 var configFile = new ConfigurationBuilder()
                //.SetBasePath(Directory.GetCurrentDirectory())                
                .SetBasePath(Directory.GetParent(AppContext.BaseDirectory).FullName)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .ReadFrom.Configuration(configFile)
            .WriteTo.Console()
            .WriteTo.Logger(lc => lc
                .Filter.ByExcluding(l => l.Level == LogEventLevel.Information || l.Level == LogEventLevel.Debug || l.Level == LogEventLevel.Warning || l.Properties["EventType"].Equals("System"))
                .WriteTo.File(Directory.GetParent(AppContext.BaseDirectory).FullName + @"\\Logs\\log-Information-.txt", rollingInterval: RollingInterval.Day))
            .WriteTo.Logger(lc => lc
                .Filter.ByIncludingOnly(l => l.Level == LogEventLevel.Error || l.Level == LogEventLevel.Fatal)
                .WriteTo.File(Directory.GetParent(AppContext.BaseDirectory).FullName + @"\\Logs\\log-Error-.txt", rollingInterval: RollingInterval.Day))
            .CreateLogger();

SelfLog.Enable(Console.Out);

try
{
    var sw = new Stopwatch();

    sw.Start();
    Serilog.Log.Logger.Information("*************************** Read DailyFile Started *****************************");

    for (global::System.Int32 i = 0; i < 100; i++)
    {
        Console.WriteLine(i);

        if (i==50)
        {
            Console.WriteLine(i--);
            Serilog.Log.Error("File Watcher Error on {2} --- {0} {EventType} for file type {1} deactivated...", sw.Elapsed, sw.ElapsedMilliseconds, i, "System");
        }

    }

    Console.ReadKey();

    sw.Stop();
    Serilog.Log.Logger.Information("File Watcher on {0} for file type {1} deactivated...", sw.Elapsed, sw.ElapsedMilliseconds);

    Serilog.Log.Logger.Information("*************************** Read DailyFile Completed *****************************");
}
catch (Exception ex)
{
    Log.Fatal(ex, "File Watcher failed with {err}...", ex.InnerException);
    throw;
}
finally
{
    Log.Information("File Watcher stopped...");
    Log.CloseAndFlush();
}

Appsettings.json 配置

"Serilog": {
  "Using": [ "Serilog.Sinks.MSSqlServer" , "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Enrichers.Environment", "Serilog.Enrichers.Thread", "Serilog.Exceptions", "Serilog.Expressions" ],
  "MinimumLevel": "Debug",
  "WriteTo": [
    {
      "Name": "Console"     
    },
    {
      "Name": "File",
      "Args": {
        "path": "Logs/SystemLog.txt",
        "rollingInterval": "Day",
        "retainedFileCountLimit": 31,
        "buffered": false,
        "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Properties} {Message:lj} {NewLine}{Exception}",
        "restrictedToMinimumLevel": "Debug"
      }
      
    ]}

它基于日志过滤器express将数据记录到单独的文件中

日志文件内容

© www.soinside.com 2019 - 2024. All rights reserved.