serilog 无法将自定义 属性 添加到数据库 table

serilog cant add custom property to database table

使用这个 serilog 配置,它可以很好地记录到数据库,但决定将 clientip 保存为新列,

已安装 Serilog.Enrichers.ClientInfo 软件包。

它将客户端 ip 作为内部文本保存到属性列,但我希望将它保存到 table 中的 clientip 列。

appsettingsjson:

{
  "AllowedHosts": "*",
  "Serilog": {
    "MinimumLevel": "Information",
    "Using": [ "Serilog.Enrichers.ClientInfo" ],
    "Enrich": [ "WithClientIp", "WithClientAgent" ],
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server= ...",
          "tableName": "Log"
        }
      }
    ]
  }
}

API:

[HttpGet]
    public IActionResult Get()
    {
        Log.Information("This is your Ip: {ClientIp}");

Program.cs:

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .AddEnvironmentVariables()
        .Build();

        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
            .CreateLogger();

            try
            {
                Log.Information("Getting the motors running...");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

如果你想要额外的列,你需要configure them

{
  "AllowedHosts": "*",
  "Serilog": {
    "MinimumLevel": "Information",
    "Using": [ "Serilog.Enrichers.ClientInfo" ],
    "Enrich": [ "WithClientIp", "WithClientAgent" ],
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server= ...",
          "tableName": "Log",
          "columnOptionsSection": {
            "additionalColumns" [
              { "ColumnName": "ClientIp", "DataType": "varchar", "DataLength": 45 }
            ]
          }
        }
      }
    ]
  }
}