使用Serilog保留EventType

问题描述 投票:1回答:1

我无法在Serilog中使用EventType功能,因为有关here的博客。

我使用以下Nuget包:

  • Serilog 2.8
  • Serilog.Settings.Configuration 3.0.1
  • Serilog.Sinks.File 4.0.0
  • Serilog.Sinks.MSSqlServer 5.1.2

首先,我创建了一个EventTypeEnricher:

public class EventTypeEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var crypto = new SimpleCrypto.PBKDF2();
        var hash = crypto.Compute(logEvent.MessageTemplate.Text);
        var numericHash = BitConverter.ToUInt32(Encoding.UTF8.GetBytes(hash), 0);
        var eventId = propertyFactory.CreateProperty("EventType", numericHash);
        logEvent.AddPropertyIfAbsent(eventId);
    }
}

这似乎有效(稍后会更多,但在该方法结束时,可以在调试时观察到EventId变量中的EventType值添加的属性)。

我创建了一个扩展方法,添加了这个更丰富的内容

    public static LoggerConfiguration WithEventType(this LoggerEnrichmentConfiguration enrichmentConfiguration)
    {
        if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
        return enrichmentConfiguration.With<EventTypeEnricher>();
    }

然后我在配置Logger时使用它:

        Log.Logger = new LoggerConfiguration()
            .Enrich.WithEventType()
            .ReadFrom.Configuration(configuration)
            .CreateLogger();

我去写这样的错误:

logger.Write(LogEventLevel.Error,
    contextFeature.Error,
    MessageTemplates.LogEntryDetailMessageTemplate,
    new LogEntryDetail
    {
        Exception = contextFeature.Error,
        Message = "Bad Stuff",
        Timestamp = DateTime.UtcNow,
        MessageTemplate = MessageTemplates.LogEntryDetailMessageTemplate,
        Severity = LogEventLevel.Error
    });

我的Serilog appsettings部分如下:

  "Serilog": {
    "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer", "MyAssembly" ],
    "Enrich": [ "EventTypeEnricher" ],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "Logs//Errorlog.log",
          "fileSizeLimitBytes": 1073741824,
          "retainedFileCountLimit": 30,
          "rollingInterval": "Day",
          "rollOnFileSizeLimit": true
        },
        "restrictedToMinimumLevel": "Verbose"
      },
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Data Source=(local);Initial Catalog=ADb;User Id=Serilog;Password=securepwd;",
          "tableName": "ErrorLogs",
          "autoCreateSqlTable": false,
          "period": 30,
          "columnOptionsSection": {
            "disableTriggers": true,
            "clusteredColumnstoreIndex": false,
            "primaryKeyColumnName": "Id",
            "addStandardColumns": [ "LogEvent" ],
            "removeStandardColumns": [ "Properties" ],
            "additionalColumns": [
              {
                "ColumnName": "EventType",
                "DataType": "int",
                "AllowNull": true
              }
            ],
            "id": { "nonClusteredIndex": true },
            "level": {
              "columnName": "Level",
              "storeAsEnum": false
            },
            "timeStamp": {
              "columnName": "Timestamp",
              "convertToUtc": true
            },
            "logEvent": {
              "excludeAdditionalProperties": true,
              "excludeStandardColumns": true
            },
            "message": { "columnName": "Message" },
            "exception": { "columnName": "Exception" },
            "messageTemplate": { "columnName": "MessageTemplate" }
          }
        },
        "restrictedToMinimumLevel": "Verbose"
      }
    ]
  }

我的数据库表如下所示:

CREATE TABLE [dbo].[ErrorLogs](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [EventType] [int] NULL,
    [Message] [nvarchar](max) NULL,
    [MessageTemplate] [nvarchar](max) NULL,
    [Level] [nvarchar](128) NULL,
    [TimeStamp] [datetime] NOT NULL,
    [Exception] [nvarchar](max) NULL,
    [Properties] [nvarchar](max) NULL,
    [LogEvent] [nvarchar](max) NULL,
 CONSTRAINT [PK_ErrorLogs] PRIMARY KEY NONCLUSTERED 

尽管自定义增强程序中的代码正在运行,但数据库中的EventType列始终为null。

它也没有写入文件接收器。

谁能看到我做错了什么或错过了什么?

干杯

serilog
1个回答
1
投票

更新到Serilog.Sinks.MSSqlServer预先发布的版本5.1.3-dev-00232修复了当前稳定版本没有读取所有columnOptionsSection部分的问题

Install-Package Serilog.Sinks.MSSqlServer -Version 5.1.3-dev-00232

以下更新的配置将在您错过EventType字段的表映射时解决您的问题

"Serilog": {
  "Using": [ "Serilog.Sinks.File", "Serilog.Sinks.MSSqlServer", "MyAssembly" ],
  "Enrich": [ "WithEventType" ],
  "MinimumLevel": {
    "Default": "Information",
    "Override": {
      "Microsoft": "Warning",
      "System": "Warning"
    }
  },
  "WriteTo": [
    {
      "Name": "File",
      "Args": {
        "path": "Logs//Errorlog.log",
        "fileSizeLimitBytes": 1073741824,
        "retainedFileCountLimit": 30,
        "rollingInterval": "Day",
        "rollOnFileSizeLimit": true
      },
      "restrictedToMinimumLevel": "Verbose"
    },
    {
      "Name": "MSSqlServer",
      "Args": {
        "connectionString": "Data Source=(local);Initial Catalog=ADb;User Id=Serilog;Password=securepwd;",
        "tableName": "ErrorLogs",
        "autoCreateSqlTable": false,
        "columnOptionsSection": {
          "disableTriggers": true,
          "clusteredColumnstoreIndex": false,
          "primaryKeyColumnName": "Id",
          "addStandardColumns": [ "LogEvent" ],
          "additionalColumns": [
            {
              "ColumnName": "EventType",
              "DataType": "int",
              "AllowNull": true
            }
          ],
          "id": {
            "columnName": "Id",
            "nonClusteredIndex": true
          },
          "eventType": {
            "columnName": "EventType"
          },
          "message": {
            "columnName": "Message"
          },
          "messageTemplate": {
            "columnName": "MessageTemplate"
          },
          "level": {
            "columnName": "Level",
            "storeAsEnum": false
          },
          "timeStamp": {
            "columnName": "TimeStamp",
            "convertToUtc": true
          },
          "exception": {
            "columnName": "Exception"
          },
          "properties": {
            "columnName": "Properties"
          },
          "logEvent": {
            "columnName": "LogEvent"
          }
        }
      }
    }
  ]
}

和Logger配置如下

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();
© www.soinside.com 2019 - 2024. All rights reserved.