【问题标题】:after await next when I try to use serilog LogContext it doesn’t push any property to log messages在等待下一次之后,当我尝试使用 serilog LogContext 时,它不会推送任何属性来记录消息
【发布时间】:2020-07-03 23:58:28
【问题描述】:
在为 Serilog 和 SEQ 设置所有内容时,我遇到了一个问题,您可能对此有答案。
我正在尝试使用 LogContext.PushProperty 向所有日志添加一些属性。但是,在我的中间件(见下图)中,LogContext 可以在 await next.Invoke() 之前将属性推送到日志。当我尝试使用 LogContext 时,在 await next 之后,它不会推送任何属性来记录消息。
问题是声明在等待下一个之前总是空的。有线索请指教?
谢谢,
【问题讨论】:
标签:
asp.net-core
logging
serilog
seq
seq-logging
【解决方案1】:
LogContext 需要与using 块结合使用,涵盖您希望属性可用的整个范围。你可能需要这样的东西:
IDisposable popContext = null;
var user2 = context.User as IAMClaimsUser;
if (user2 != null && !string.IsNullOrEmpty(user2.FirstName))
{
popContext = LogContext.PushProperty("UserEmail", user2.Email);
}
using (popContext)
{
// `UserEmail` will be attached to events logged in this block
await next();
}