How to safely set log4net.LogicalThreadContext.Properties["UserId"]

Viewed 19

We have a multi-tenant, asp.net mvc c# app that we log via log4net using SQL server as the data store. We have this logging all over in our code. But now I'd like to capture some additional properties to help with diagnosing. i.e. capture the logged in UserId. Long term I want the user to actually be able to view these (well maybe), so I need an accurate UserId associated with each log written in the SQL DB.

I'm setting the LogicalThreadContext properties as after reading about the different contexts, this one would be the most applicable that most closely matches a request. Is that correct?

I set this at some early part of the logic flow:

log4net.LogicalThreadContext.Properties["UserId"] = loggedInUser.Id;

However, I'm noticing that the log does not always contain the respective, proper UserId. Is this possible?

What is the best way to achieve this with absolute accuracy? Should I create a wrapper around logger.Info, etc which accepts UserId and then immediately call the log statement? Is that even safe?

log4net.LogicalThreadContext.Properties["UserId"] = loggedInUser.Id;
logger.Info("Test Log");

Or is there a way to use an instance based logger that I'm missing that takes additional properties in the constructor, etc?

Also, once you set the log4net.LogicalThreadContext.Properties, they live just for that single request, correct? So we don't have to worry about ALWAYS setting these properties for fear of them still containing the prior values and in those cases the value will just be NULL?

0 Answers
Related