Hi,
NLog provides a feature to PushProperty into the ScopeContext (https://github.com/NLog/NLog/wiki/Context#scopecontext-properties).
We want to add e.g. the user-id to this scope context on a request level, so that every log statement within a service has this user-id property.
The idea was to use pre request filter to add the property to the scope context. Because PushProperty is a disposable, we store that IDisposable in IRequest.Items, just to be able to Dispose it in a ResponseFilter.
Sample Code:
public static class UserLoggingContextFilter
{
public const string ContextKey = "user-log-context";
public static void RequestFilter(IRequest request, IResponse response, object _)
{
var session = (AuthUserSession) request.GetSession();
request.Items[ContextKey] = ScopeContext.PushProperties(new[]
{
new KeyValuePair<string, object>("UserId", session.UserAuthId),
new KeyValuePair<string, object>("UserName", session.UserName),
new KeyValuePair<string, object>("Session", session.Id[..6]),
});
}
public static void ResponseFilter(IRequest request, IResponse response, object _)
{
(request.Items[ContextKey] as IDisposable)?.Dispose();
}
}
We noticed that Properties added in the RequestFilter aren’t visibile in the Service and were wondering why this is the case?
It seems that the RequestFilter and service implementation doesn’t share the same ScopeContext. As far as we understand ScopeContext uses AsyncLocal as storage.
Overrideing ServiceRunner.OnBeforeExecute to push properties there works.
We’re expecting to be able such Context between PreRequestFilters and the service implementation. What am I missing? I couldn’t figure it out in the docs.