ASP.NET Core 3-Serilog如何在appsettings.json文件中配置Serilog.Sinks.Map?

时间:2019-12-22 22:36:00

标签: json serilog appsettings asp.net-core-3.1

我今天遇到了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。 Program.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 Sink接口时,如何管理最旧事件的自动清除/删除,即DB应该最多存储1,000,000个事件,然后自动覆盖最旧事件首先,预先感谢

1 个答案:

答案 0 :(得分:0)

我相信当前无法在json中配置标准Map调用,因为它依赖于目前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需要了解您的程序集具有这些扩展名,以便在解析阶段加载它们。根据文档,您需要在*.Serilog.*程序集上具有这些扩展名,或者在json上添加Using子句:

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

有关这些约束的更多信息,请参见: