簡體   English   中英

.NET Serilog PostgresSql 接收器中的核心自定義列

[英].NET Core custom columns in Serilog PostgresSql sink

我在我的 .NET 核心應用程序中使用 Serilog。 我已將自定義列添加到默認列列表中。

這是我的配置:

appsettings.json

"Serilog": {
    "Using": [ "Serilog.Sinks.PostgreSQL" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "D:\\Logs\\logs.txt",
          "outputTemplate": "{Timestamp} {Message}{NewLine:1}{Exception:1}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "D:\\Logs\\logs.json",
          "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
        }
      },
      {
        "Name": "PostgreSQL",
        "Args": {
          "connectionString": "my-connection",
          "tableName": "public.mylogs",
          "needAutoCreateTable": true,
          "batchPostingLimit": 1,
          "restrictedToMinimumLevel": "Information",
          "removeStandardColumns": [ "MessageTemplate" ],
          "customColumns": [
          {
            "ColumnName": "username",
            "DataType": "varchar",
            "DataLength": 50
          }
        ]
        }
      }
    ],

    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ],
    "Properties": {
      "ApplicationName": "Shamis-Radio-Control-System"
    }
  },

Program.cs

public static IConfiguration Configuration { get; private set; }

public static void Main(string[] args)
{
    Configuration = new ConfigurationBuilder()
        //.SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", true, true)
        //.AddCommandLine(args)
        //.AddEnvironmentVariables()
        .Build();

    // Configure serilog
    Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

    try
    {
        Log.Information("Starting up...");
        CreateHostBuilder(args).Build().Run();
        Log.Information("Shutting down...");
    }
    catch (Exception ex)
    {
        Log.Fatal(ex, "Api host terminated unexpectedly");
    }
    finally
    {
        Log.CloseAndFlush();
    }

    CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>()
                //.UseConfiguration(Configuration)
                .UseSerilog();
            });

這是我的 controller:

try
{
    using (LogContext.PushProperty("username", "Waleed"))
    {
        _ILogger.LogInformation("{Message}", "Starting up...");
    }     
}
catch (Exception ex)
{
    using (LogContext.PushProperty("username", "User1"))
    {
        _ILogger.LogInformation("{Message}", "Starting up...");
    }           
}

運行項目將生成新表mylogs ,但不會刪除列MessageTemplate並且不會生成自定義列username

我嘗試手動添加列“用戶名”,但總是值 null。

請幫我解決這個問題 - 謝謝大家。

也許您找到了解決方案,但這可以幫助您。 安裝 nuget: Serilog.Sinks.PostgreSQLSerilog.Sinks.PostgreSQL.Configuration

添加 SelfLog 以查看任何錯誤(不是必需的,但可以幫助您):

Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine(msg));

這是您可以調整的配置(添加或刪除列,更改 ColumnWriters...):

    "Serilog": {
    "Using": [ "Serilog.Sinks.PostgreSQL.Configuration" ], // THIS IS IMPORTANT
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithEnvironmentUserName",
      "WithExceptionDetails",
      "WithDemystifiedStackTraces"
    ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information",
        "System": "Warning",
        "Microsoft.AspNetCore.Authentication": "Information",
        "Microsoft.EntityFrameworkCore": "Error"
      }
    },
    "WriteTo": [
      {
        "Name": "PostgreSQL",
        "Args": {
          "connectionString": "Context",
          "tableName": "\"Logs\"",
          "needAutoCreateTable": true
        }
      }
    ]
  },
  "Columns": {
    "\"Message\"": "RenderedMessageColumnWriter",
    "\"MessageTemplate\"": "MessageTemplateColumnWriter",
    "\"Level\"": {
      "Name": "LevelColumnWriter",
      "Args": {
        "renderAsText": true,
        "dbType": "Varchar"
      }
    },
    "\"TimeStamp\"": "TimestampColumnWriter",
    "\"Exception\"": "ExceptionColumnWriter",
    "\"Properties\"": "LogEventSerializedColumnWriter",
    "\"PropsTest\"": {
      "Name": "PropertiesColumnWriter",
      "Args": {
        "dbType": "Json"
      }
    },
    "\"MachineName\"": {
      "Name": "SinglePropertyColumnWriter",
      "Args": {
        "propertyName": "MachineName",
        "writeMethod": "Raw"
      }
    }
  }

還要檢查此鏈接: https://github.com/b00ted/serilog-sinks-postgresql

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM