Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ScopeContext properties in AsyncTaskTarget

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.

like image 712
marsze Avatar asked Oct 17 '25 19:10

marsze


1 Answers

In your Target-constructor enable the option:

  • IncludeScopeProperties = true;

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 )

like image 50
Rolf Kristensen Avatar answered Oct 19 '25 10:10

Rolf Kristensen