Skip to content

Add support for context properties #5

Open
@isak1080

Description

@isak1080

In NLog 5 it's possible to add scoped context properties that are automatically attached to all log messages for the lifetime of the scope.

A text-book use case would be in an ASP.Net controller to setup the scope at the beginning of the request, and have all log messages generated within that request to hold some common properties (even if they are not part of the log messages).
This makes it very easy to add things like authenticated username, track "activities" (assign a GUID to each request/operation) etc.

I tested this by cloning this repo and modifying BetterStackLogsTarget.Write() to include the following:

if (IncludeScopeProperties)
{

    var scopeProperties = global::NLog.ScopeContext.GetAllProperties();

    if (scopeProperties != null)
    {
        var scopeDict = new Dictionary<string, object>();

        foreach (var scopeProperty in scopeProperties)
        {
            string key = scopeProperty.Key;
            if (string.IsNullOrEmpty(key)) continue;
            scopeDict[key] = scopeProperty.Value;
        }

        contextDictionary["scope"] = scopeDict;
    }
}

This worked fine in my testing

Note: This would require an update to NLog 5.x (which has been out since 2022)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions