- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
根据 this文章中,您可以将请求 ID 附加到 Serilog 中的环境上下文(LogContext
),如下所示:
using (LogContext.PushProperty("RequestId", Request.Id))
{
// Process request; all logged events will carry `RequestId`
Log.Information("Adding {Item} to cart {CartId}", item, cart.Id);
}
这很好,而且似乎有效。我有两种情况需要这个:
让我感到困惑的是,如果多个请求同时命中 API,或者我们同时处理多条消息,会发生什么情况。由于 LogContext
是一个静态类,我是否可以不小心用另一个线程的值覆盖 LogContext
中的 RequestId
属性,而不是最初设置属性(property)?
假设线程 1 将 RequestId
设置为 1
。在完成之前,线程 2 将 RequestId
设置为 2
,因为我们收到了另一个请求。线程 1 现在会在记录时使用 2
作为 RequestId
的值吗?我猜它不会,但有人可以解释为什么吗?根据这个this , 将与现有属性同名的属性压入堆栈会覆盖它:
Pushing property onto the context will override any existing properties with the same name, until the object returned from PushProperty() is disposed, as the property A in the example demonstrates.
Serilog 是否对从 LogContext.PushProperty(...)
方法返回的每个句柄有一个堆栈?有什么方法可以重写 RequestId
,或许不需要再次调用 LogContext.PushProperty("RequestId", Request.Id)
?
最佳答案
LogContext is thread-safe via AsyncLocal/ThreadStatic .每个线程都有自己的 LogContext,尽管它是通过静态类访问的。请求不共享相同的 LogContext。
关于c# - Serilog 中环境 LogContext 的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65887281/
我是一名优秀的程序员,十分优秀!