Mehmet Yener Yılmaz
Mehmet Yener Yılmaz

Reputation: 251

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

Upvotes: 2

Views: 1264

Answers (1)

ESG
ESG

Reputation: 9425

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
              }
            ]
          }
        }
      }
    ]
  }
}

Upvotes: 1

Related Questions