json - 如何在 appsettings.json 中设置我自己的 KeyGenerator 实例?

标签 json azure-table-storage serilog asp.net-core-2.0

我已经问过这个问题了here但我觉得 Stackoverflow 可能会更快。这就是我尝试在我的 json 配置文件中执行此操作的方式:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.AzureTableStorage" ],
    "WriteTo": [
      {
        "Name": "AzureTableStorage",
        "Args": {
          "storageTableName": "Logs",
          "connectionString": "*************",
          "keyGenerator": "MyApp.Serilog.AzureTableStorage.MyKeyGenerator"
        }
      }
    ],
    "MinimumLevel": "Verbose"
  }
}

这是我的生成器实现:
public class MyKeyGenerator : IKeyGenerator
{
    public string GeneratePartitionKey(LogEvent logEvent)
    {
        return Environment.MachineName;
    }

    public string GenerateRowKey(LogEvent logEvent, string suffix = null)
    {
        return SUID.nextId().ToString();
    }
}

显然,.ReadFrom.Configuration操作抛出 InvalidCastException ,因为它试图将字符串内容放入 IKeyGenerator范围。

我应该如何设置 keyGenerator确保 MyKeyGenerator 的实例的参数创建类并赋予该参数?

最佳答案

我克隆了serilog-settings-configuration在深入研究代码后,我发现当实际参数是接口(interface)时,他们期望 JSON 设置值(参见 StringArgumentValue.cs,第 57 至 74 行)。

引用要作为参数传递的类型的正确方法是给出 用逗号分隔的完整类和程序集名称 .那个类必须有一个公共(public)的默认构造函数 也是。

前任:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.AzureTableStorage" ],
    "WriteTo": [
      {
        "Name": "AzureTableStorage",
        "Args": {
          "storageTableName": "Logs",
          "connectionString": "*************",
          "keyGenerator": "MyApp.Serilog.AzureTableStorage.MyKeyGenerator, MyApp"
        }
      }
    ],
    "MinimumLevel": "Verbose"
  }
}

这样,配置器就可以正确地实例化类!

关于json - 如何在 appsettings.json 中设置我自己的 KeyGenerator 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082251/

相关文章:

javascript - 使用 jquery 或 javascript 从 json 变量数据获取值

azure - 使用 az 存储实体查询时出现不一致的授权警告和错误

python-3.x - 分区键作为 python azure 存储表中的变量

nlog - 使用自定义目标将所有 NLog 输出重定向到 Serilog

wcf - 在 WCF 中使用 Serilog

javascript - 将用户输入的数据推送到 JavaScript 内的 JSON 中

json - Play 案例类的json读取和默认参数?

json - Http 正文中的 Post 字符串值

azure - 具有 PK 和 RK 范围的 Azure 表存储的共享访问签名

c# - 将 Serilog ILogger 添加到静态类