简体   繁体   English

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

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

I am using Serilog in my .NET Core application.我在我的 .NET 核心应用程序中使用 Serilog。 I have added custom columns to the default list of columns.我已将自定义列添加到默认列列表中。

This is my configuration:这是我的配置:

appsettings.json : 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 : 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();
            });

This is my controller:这是我的 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...");
    }           
}

Running the project will generate the new table mylogs , but not delete column MessageTemplate and not generate custom column username .运行项目将生成新表mylogs ,但不会删除列MessageTemplate并且不会生成自定义列username

I try added manually column "username" but always the value null.我尝试手动添加列“用户名”,但总是值 null。

Please help me to resolve this issue - thanks all.请帮我解决这个问题 - 谢谢大家。

Maybe you found the solution but, this could help you.也许您找到了解决方案,但这可以帮助您。 Install nugets: Serilog.Sinks.PostgreSQL and Serilog.Sinks.PostgreSQL.Configuration .安装 nuget: Serilog.Sinks.PostgreSQLSerilog.Sinks.PostgreSQL.Configuration

Add SelfLog to see errors if any (not necessary but can help you):添加 SelfLog 以查看任何错误(不是必需的,但可以帮助您):

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

Here is configuration you can adjust (add or remove columns, change ColumnWriters...):这是您可以调整的配置(添加或删除列,更改 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"
      }
    }
  }

Check this link also: https://github.com/b00ted/serilog-sinks-postgresql还要检查此链接: https://github.com/b00ted/serilog-sinks-postgresql

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM