使用Serilog保留EventType

时间:2019-03-19 02:11:45

标签: serilog

我无法让EventType功能在Serilog中正常工作,就像关于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应用程序设置部分如下:

  "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列始终为空。

它也不会写入文件接收器。

任何人都可以看到我在做错或丢失的事情吗?

欢呼声

1 个答案:

答案 0 :(得分: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"
          }
        }
      }
    }
  ]
}

记录器配置如下

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