Serilog.Sinks.MSSqlServer 未填写自定义列

Serilog.Sinks.MSSqlServer not filling custom columns

我环顾四周,但找不到可行的解决方案,并且由于所有示例看起来都很相似,所以我认为一定是我忽略了一些明显的东西。 另请注意,这是我的第一个真正的项目 using.NET Core 和 Serilog。

问题

我正在尝试将一些自定义属性记录(使用 serilog)到数据库中它们自己的列中,如 appsettings.json 中所定义,并通过管道上的中间件添加。但是值仍然为 NULL,即使在属性 XML 列中正确填写了相同的项目。

所以我有经过身份验证的用户的预期新属性:

<properties>
    <property key="UserId">ff88ddb9-6f5a-4ad5-a2a8-1d016ff99398</property>
    <property key="UserName">ernst</property>
<properties>

但我也想将这些值添加到它们自己的列中,以进行一些查询优化。

密码

代码是 .NET Core 2.1+,我已经设置了 Serilog,如 https://github.com/serilog/serilog-aspnetcore/blob/dev/samples/SimpleWebSample/Program.cs 所示:

private 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 int Main(string[] args)
{
  Log.Logger = new LoggerConfiguration()
      .ReadFrom.Configuration(Configuration)
      .Enrich.FromLogContext()
      .MinimumLevel.Debug()
      .CreateLogger();
  try 
  {
    Log.Information($"Starting web host in {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"} environment, version {Util.Version.Long}");
    BuildWebHost(args).Run();
    return 0;
  }
  catch (Exception ex)
  {
    Log.Fatal(ex, "Host terminated unexpectedly");
    return 1;
  }
  finally
  {
    Log.CloseAndFlush();
  }
}

 private static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseConfiguration(Configuration)
                .UseSerilog()
                .CaptureStartupErrors(true)
                .Build();

要添加我在中间件中使用 LogContext.PushProperty 的信息。

相关件配置:

"Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": "Debug",
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Data Source=localhost;Database=MyDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
          "tableName": "SeriLog_Custom",
          "autoCreateSqlTable": true,
          "restrictedToMinimumLevel": "Information",
          "columnOptionsSection": {
            "customColumns": [
              {
                "ColumnName": "UserId",
                "DataType": "nvarchar",
                "DataLength": 450,
                "AllowNull": true
              },
              {
                "ColumnName": "UserName",
                "DataType": "nvarchar",
                "DataLength": 256,
                "AllowNull": true

              }
            ]
          }
        }
      }
    ]
  }

此外,除了不填充自定义列外,数据库也是以标准方式创建的,没有这些列,因此我手动添加了它们。

这可能是配置问题?

SQL 创建 table:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[SeriLog_Custom](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Message] [nvarchar](max) NULL,
    [MessageTemplate] [nvarchar](max) NULL,
    [Level] [nvarchar](128) NULL,
    [TimeStamp] [datetime] NOT NULL,
    [Exception] [nvarchar](max) NULL,
    [Properties] [xml] NULL,
    [UserId] [nvarchar](450) NULL,
    [UserName] [nvarchar](256) NULL,
 CONSTRAINT [PK_SeriLog_Custom] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

现在我可以通过以下方式获得所需的信息:

SELECT [Id]
      ,[Message]
      ,[MessageTemplate]
      ,[Level]
      ,[TimeStamp]
      ,[Exception]
      ,[UserId]
      ,[UserName]
      ,[Properties].value('(//property[@key="UserName"]/node())[1]', 'nvarchar(max)') as UserName
      ,[Properties]
  FROM [ECSControl].[dbo].[SeriLog_ECMonitor]
  where [Properties].value('(//property[@key="UserName"]/node())[1]', 'nvarchar(max)') = 'ernst'
  order by id desc;

但我想通过以下方式访问它:

SELECT [Id]
      ,[Message]
      ,[MessageTemplate]
      ,[Level]
      ,[TimeStamp]
      ,[Exception]
      ,[UserId]
      ,[UserName]
      ,[Properties]
  FROM [ECSControl].[dbo].[SeriLog_ECMonitor]
  where  UserName = 'ernst'
  order by id desc;

Serilog.Sinks.MSSqlServer (5.1.2) 的最新稳定版本没有 Microsoft.Extensions.Configuration 支持。与 Serilog.Settings.Configuration (2.6.1) (ref) 的最新稳定版本相同。

更新到预发布版本 Serilog.Sinks.MSSqlServer 5.1.3-dev-00204Serilog.Settings.Configuration 3.0.0-dev-00119 解决了这个问题。