Is there a way to set a context property value in log4net at logger level? We have scopes at thread context and global context and so on. I was wondering if there is a way to set a context variable at the logger instance level?
I know such thing does not exist but to make my point, it would be like
private static ILog _Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
_Log.LoggerContext.Properties["myVar"] = "someValue";
//now every log with this logger will use somevalue for the myVar property.
Is there a way to do such thing?
As far as I know, that capability does not exist in log4net (or NLog for that matter). I do have an idea that should work. I don’t know if it is a “good” idea or not, I will leave that for you to decide…
Briefly, you could write a custom PatternLayoutConverter (see this post for one example of how to do this). This converter will look for a “context” in your own static dictionary (similar to the static dictionary contexts that log4net already has). The “context” will be stored by logger name. The value in the dictionary will be another dictionary that will hold your variables.
This a little bit more involved than I am prepared to get into right now, but I will try to give some good pseudocode to show how it might work…
UPDATE:
I have added an implementation that works (at least in the minimal testing that I have done). I have defined a “context” to hold a property bag for each logger. I have also implemented a PatternLayoutConverter to retrieve the properties for a given logger.
(The code formatting does not seem to be honoring indentation).
Configure the appender to use the PatternLayoutConverter:
How to set the properties for a logger:
The output:
Good luck!