I'm having trouble getting the EventType feature working in Serilog, as blogged about here.
I am using the following Nuget packages:
First up, I created an 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);
}
}
This seems to work (more on that later, but at the end of that method, a property is added with an EventType value in the EventId variable can be observed while debugging).
I created an extension method which adds this enricher:
public static LoggerConfiguration WithEventType(this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
return enrichmentConfiguration.With<EventTypeEnricher>();
}
I then use that when I configure the Logger:
Log.Logger = new LoggerConfiguration()
.Enrich.WithEventType()
.ReadFrom.Configuration(configuration)
.CreateLogger();
I go to write the error like this:
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
});
My Serilog appsettings section is as follows:
"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"
}
]
}
My database table looks like this:
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
The EventType column in the database is always null, despite the code in the custom enricher running.
It is not written to the file sink either.
Can anyone see what I am doing wrong or missing?
Cheers
Updating to Serilog.Sinks.MSSqlServer version 5.1.3
fixed the issue as current stable version 5.1.2
not reading all columnOptionsSection
section
Install-Package Serilog.Sinks.MSSqlServer -Version 5.1.3
And below updated configuration will fix your issue as you miss table mapping for EventType
field
"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"
}
}
}
}
]
}
And Logger configuration as below
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();