在AsynctaskTarget中获取ScopeContext属性

发布于 2025-02-12 02:22:55 字数 1017 浏览 1 评论 0 原文

我正在实施一个自定义 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问题但是我在那里没有找到真正的解决方案。

I am implementing a custom NLog AsyncTaskTarget, and I need to retrieve values that I have added using Microsoft.Extensions.Logging.ILogger.BeginScope:

using (var scope = logger.BeginScope(new []
{
    new KeyValuePair<string, object>("userId", this.UserId)
}))
{
    logger.Log(..);
}

Rendering this in a layout using ${mdlc:userId} works fine, but I would like to get them directly from MappedDiagnosticsLogicalContext or ScopeContext.

This is what I've tried:

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);
}

How do I get the userId value from the scope?

NLog Version: 5.0.1 (newest)

This GitHub issue is related to this problem, but I found no real solution there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小姐丶请自重 2025-02-19 02:22:55

在您的目标 - 构建器中启用选项:

然后,您可以使用

protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
{
    var contextProperties = GetScopeContextProperties(logEvent);
    contextProperties?.TryGetValue("userid", out var userId);
}

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:

protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken token)
{
    var contextProperties = GetScopeContextProperties(logEvent);
    contextProperties?.TryGetValue("userid", out var userId);
}

You can also get a combined dictionary of all properties, by using GetAllProperties() and the do the lookup (Still need to enable IncludeScopeProperties )

小姐丶请自重 2025-02-19 02:22:55

You could use GetAllProperties method to get dictionary of all configured properties for logEvent, and then retrieve specific property from the dictionary. Just enable IncludeScopeProperties of the target in NLog configuration.

晌融 2025-02-19 02:22:55

完整解决方案:

using NLog;
using NLog.Targets;

class AsyncScopeTarget : AsyncTaskTarget
{
    public AsyncScopeTarget()
    {
        this.IncludeScopeProperties = true;
    }

    protected override bool SerializeScopeContextProperty(LogEventInfo logEvent, string name, object value, out object serializedValue)
    {
        // return the original (immutable) value
        serializedValue = value;
        return true;
    }

    protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
    {
        var scopeValues = GetScopeContextProperties(logEvent);
        if (scopeValues is not null)
        {
            scopeValues.TryGetValue("name", out object? scopeValue);
        }
    }
}

(注意:还考虑 this post。)

Full solution:

using NLog;
using NLog.Targets;

class AsyncScopeTarget : AsyncTaskTarget
{
    public AsyncScopeTarget()
    {
        this.IncludeScopeProperties = true;
    }

    protected override bool SerializeScopeContextProperty(LogEventInfo logEvent, string name, object value, out object serializedValue)
    {
        // return the original (immutable) value
        serializedValue = value;
        return true;
    }

    protected override async Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken)
    {
        var scopeValues = GetScopeContextProperties(logEvent);
        if (scopeValues is not null)
        {
            scopeValues.TryGetValue("name", out object? scopeValue);
        }
    }
}

(Note: Also consider this post.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文