I have this setup in appsettings.json for my Serilog installation
"Serilog": {
"MinimumLevel": "Information",
"Enrich": [ "LogUserName" ],
"Override": {
"Microsoft": "Critical"
},
"WriteTo": [
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "Server=.\\SQLEXPRESS;Database=Apple;Trusted_Connection=True;MultipleActiveResultSets=true;,
"schemaName": "Apple",
"tableName": "EventLogs",
"columnOptionsSection": {
"customColumns": [
{
"ColumnName": "UserName",
"DataType": "nvarchar",
"DataLength": 256,
"AllowNull": true
}
]
}
}
}
]
},
I also have a custom enricher called LogUserName that is supposed to add the users username to a column called UserName in the db.
This is the enricher:
public class LogUserName
{
private readonly RequestDelegate next;
public LogUserName(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
LogContext.PushProperty("UserName", context.User.Identity.Name);
await next(context);
//return next(context);
}
}
I have added .Enrich.FromLogContext() to my Program.cs.
So far I am able to see the UserName in the property tag but I am unable to push it to the column.
EDIT:
I use this model for my logs to the database:
public class EventLogs
{
[Key]
public int Id { get; set; }
public string Level { get; set; }
public DateTime TimeStamp { get; set; }
public string UserName { get; set; }
public string Properties { get; set; }
public string LogEvent { get; set; }
public string Exception { get; set; }
public string Message { get; set; }
public string MessageTemplate { get; set; }
}