在AsynctaskTarget中获取ScopeContext属性
我正在实施一个自定义 nlog asynctaskTarget
,我需要检索我使用 microsoft.extensions.logging.ilogger.beginscope.beginscope
::
using (var scope = logger.BeginScope(new []
{
new KeyValuePair<string, object>("userId", this.UserId)
}))
{
logger.Log(..);
}
使用 $ {mdlc:userId}
在布局中渲染此功能,但是我想直接从 mappeddiagnosticsLogicalContext
或 scopeceContext
中直接获取它们。
这是我尝试的:
protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
{
// returns null
ScopeContext.TryGetProperty("userId", out var userId);
userId = MappedDiagnosticsLogicalContext.GetObject("userId");
// this works fine
var message = this.Layout.Render(logEvent);
}
如何从范围中获取 userId
值?
nlog版本:5.0.1(最新)
此 github问题但是我在那里没有找到真正的解决方案。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的目标 - 构建器中启用选项:
然后,您可以使用
https://nlog-project.org/documentation/v5.0.0.0/html/m_nlog/m_nlog_targets_targets_targetwithcontextexcopecopecopecopecopecopecopecontextproperties.htm还可以通过使用和DO查找(仍然需要启用)
In your Target-constructor enable the option:
And then you can use GetScopeContextProperties() method:
You can also get a combined dictionary of all properties, by using GetAllProperties() and the do the lookup (Still need to enable IncludeScopeProperties )
您可以使用 logevent 的所有配置属性的字典,然后从字典中检索特定属性。只需启用 nlog配置。
You could use
GetAllProperties
method to get dictionary of all configured properties forlogEvent
, and then retrieve specific property from the dictionary. Just enableIncludeScopeProperties
of the target in NLog configuration.完整解决方案:
(注意:还考虑 this post。)
Full solution:
(Note: Also consider this post.)