2

I'm referring to the excellent post :

Log4Net, how to add a custom field to my logging

But it doesn't give me the entire solution.

No problem to log a string like "This is a test", but If I want to log a variable, it's responding (null).

Here is my snipped code not working:

log4net.GlobalContext.Properties["versionid"] = Variables.IDVERSION;

Here is my working snipped code :

log4net.GlobalContext.Properties["versionid"] = " This is a test";

Although, IDVERSION is a public property systematically updated in my code c#.

Has anyone an idea How to solve this problem? I think I'm near the solution.

Community
  • 1
  • 1
GYCO50
  • 45
  • 1
  • 8
  • 1
    Do you set the value of `Variables.IDVERSION` before or after assigning it to the log4net property? Note that log4net won't track any new values you give it - you'll need to update the log4net property each time too. – James Thorpe Mar 04 '16 at 11:36
  • I assigned the variable after in my first attempt.Now,I assigning the value of the variable before updating the log4net property..and it's working perfectly well. Simple and logical. Thanks for your help. I should think a bit more next time.:-) – GYCO50 Mar 04 '16 at 11:48

2 Answers2

5

At the moment you call this:

log4net.GlobalContext.Properties["versionid"] = Variables.IDVERSION;

The property will hold the value of Variables.IDVERSION at that moment. It won't automagically track updates to the Variables.IDVERSION variable.

So if you set Variables.IDVERSION later in code, you need to do the assignment to Properties["versionid"] again.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Good explanation. In first attempt, I assigned the variable after. Now,I assigning the value of the variable before updating the log4net property..and it's working perfectly well. Simple and logical. Thanks for your help. I should think a bit more next time.:-) – GYCO50 Mar 04 '16 at 13:50
0

When log4net evaluates context properties it calls the .ToString() method of the property value. So you could have dynamic property values if you have a reference as a value (I believe your idversion field is a value type eg. Int?).

See https://logging.apache.org/log4net/release/manual/contexts.html for more details

ubi
  • 4,041
  • 3
  • 33
  • 50
  • Thanks, It was just a question of order in declaring variable first and then refreshing the log4net custom property. Working now as expected. Definitively log4net is great. – GYCO50 Mar 04 '16 at 13:56