Open
Description
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
Labels
No labels