5

我今天遇到了 Serilog.Sinks.Map 插件,它将解决我将特定日志事件路由到特定接收器接口的挑战。在我的环境中,我正在写入日志文件以及使用 SQL 接口。我只希望将某些日志写入 SQL Server。

阅读作者在 GitHub 上的说明,我只能在 Program.CS 中看到通过 C# 实现 LoggerConfiguration 的示例,但我使用的是 appsettings.json 文件,不确定从提供的示例更改为所需的 json 格式.

Serilog 在 GitHub 上给出的示例:

Log.Logger = new LoggerConfiguration()
.WriteTo.Map("Name", "Other", (name, wt) => wt.File($"./logs/log-{name}.txt"))
.CreateLogger();

我当前的配置:注意我还没有在我的代码中实现 Sinks.Map。程序.CS 文件:

public static void Main(string[] args)
{
    // Build a configuration system with the route of the app settings.json file.
    // this is becuase we dont yet have dependancy injection available, that comes later.
    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(configuration)
        .CreateLogger();

    var host = CreateHostBuilder(args).Build();
}

这是我的 appsettings.json 文件。我希望能够将接收器名称“MSSqlServer”配置为特殊路由,然后将标准文件附加程序接收器用于所有其他常规日志记录。

    "AllowedHosts": "*",
  "Serilog": {
    "Using": [],
    "MinumumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": {
          //"path": "C:\\NetCoreLogs\\log.txt", // Example path to Windows Drive.
          "path": ".\\Logs\\logs.txt",
          //"rollingInterval": "Day", // Not currently in use.
          "rollOnFileSizeLimit": true,
          //"retainedFileCountLimit": null, // Not currently in use.
          "fileSizeLimitBytes": 10000000,
          "outputTemplate": "{Timestamp:dd-MM-yyyy HH:mm:ss.fff G} {Message}{NewLine:1}{Exception:1}"
          // *Template Notes*
          // Timestamp 'G' means UTC Time
        }
      },
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "DefaultConnection",
          "schemaName": "EventLogging",
          "tableName": "Logs",
          "autoCreateSqlTable": true,
          "restrictedToMinimumLevel": "Information",
          "batchPostingLimit": 1000,
          "period": "0.00:00:30"
        }
      }
      //{
      //  "Name": "File",
      //  "Args": {
      //    "path": "C:\\NetCoreLogs\\log.json",
      //    "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
      //  }
      //}
    ]
  }

最后,如果我可以就该主题提出另一个快速问题,当使用 SQL 接收器接口时,如何管理最旧事件的自动清除/删除,即 DB 应该只存储最多 1,000,000 个事件,然后首先自动覆盖最旧的事件,谢谢提前

4

1 回答 1

1

我相信目前不可能Map在 json 中配置标准调用,因为它依赖于一些目前不支持序列化的类型,例如Action<T1, T2>. 我创建了一个问题来在存储库本身中讨论这个问题:

但是,通过创建自定义扩展方法,仍然可以在 Json 中获得一些功能。在您的特定情况下,它将是这样的:

    public static class SerilogSinkConfigurationExtensions
    {
        public static LoggerConfiguration MapToFile(
            this LoggerSinkConfiguration loggerSinkConfiguration,
            string keyPropertyName,
            string pathFormat,
            string defaultKey)
        {
            return loggerSinkConfiguration.Map(
                keyPropertyName,
                defaultKey,
                (key, config) => config.File(string.Format(pathFormat, key));
        }
    }

然后,在您的 json 文件中,添加如下部分:

    "WriteTo": [
      ...
      {
        "Name": "MapToFile",
        "Args": {
          "KeyPropertyName": "Name",
          "DefaultKey": "Other",
          "PathFormat": "./logs/log-{0}.txt"
        }
      }
    ]

为了使这些自定义正常工作,Serilog 需要了解您的程序集具有这些类型的扩展,以便在解析阶段加载它们。根据文档,您要么需要在程序集上具有这些扩展,要么在 json 上*.Serilog.*添加子句:Using

// Assuming the extension method is inside the "Company.Domain.MyProject" dll
"Using": [ "Company.Domain.MyProject" ]

有关这些约束的更多信息,请点击此处:

于 2020-08-10T12:18:50.903 回答