Serilog.Sinks.Elasticsearch 写username到 ES失败

发布时间 2023-04-07 21:43:17作者: qgbo

Using the lib: Serilog.Sinks.Elasticsearch and ECS-dotnet which provide the ecs format, we can write log into es in ECS format.

I have been able to overall link trace,  now, I want to record the username if user has logged.

Astonoshingly, sometime, it works,then fail!

for a long time, I think this because the ecs format do some odd thing.

then I find the root cause:

My application  record log in es and file.

if I just log in file, the username can be recorded, if the log in es, the use name will lose.

username can be seen in middware, but when to send to es, the httpcontext.user become lost!

Loging in  file use Serilog.Sinks.File.  Meanwhile  Logging in ES use Serilog.Sinks.Elasticsearch which dot use the request thread. So the IHttpContextAccessor.Httpcontext will become null!

I konw he ThreadId was recorded in es, so it seems that the user name also can be recorded!

At least, we can add a middleware to recored the property