Search code examples
asp.net-coreserilog

serilog cant add custom property to database table


using this serilog config and it logs to database fine but decided to save clientip as new column,

installed Serilog.Enrichers.ClientInfo package.

it saves client ip to properties column as a inner text, but I expected to save it to clientip column in table.

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();
            }
        }

Solution

  • If you want extra columns, you need to 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",
                    "PropertyName": "ClientIp",
                    "DataType": "varchar",
                    "DataLength": 45
                  }
                ]
              }
            }
          }
        ]
      }
    }