1

I'm trying to figure out how to set a per-user session using ThreadContext.Properties.

When a user has logged in on a website the userid is stored in session. This value i then want to append to ThreadContext.Properties["UserID"] upon after successful login.

I'm saving log entries to db using the adonetappender and i use the %property{userid} to retrieve the value. But sometimes this value reads null.

So basically what i want is:

1) Create the

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

on those pages that i want to log.

2) Upon successful login i need to store in ThreadContext.Properties["UserID"] a value that is always there throughout the users session and can be utlized both from pages i log from and also from the Application_Error(...) in global_asax. What is the lifespan of this ThreadContext anyway? I can't really use GlobalContext as far as i know.

3) I don't want to reassign the value on every log statement.

Hope you'll understand where i'm going.

//Daniel

wageoghe
  • 27,390
  • 13
  • 88
  • 116

1 Answers1

0

See my answer here:

Capture username with log4net

For some ideas that might help you. Read all the way to the end, as the last idea is probably the simplest and might meet your needs.

To summarize, I first proposed writing a custom PatternLayoutConverter, HttpContextPatternLayoutConverter that would allow logging values stored in an HttpContext.

Towards the end of my answer, I proposed a solution based on another blog posting (linked in my original answer) that shows how to write a class that can be stored in the GlobalDiagnosticContext (or ThreadDiagnosticContext for that matter). When you tell log4net to log that GlobalDiagnosticContext parameter, log4net accesses the object and calls its ToString method. The object itself just extracts a value from the HttpContext.

So, if you are able to use HttpContext to store the information that you want to log, then my linked answer might be of some use to you. If you are not able to use HttpContext to store the information, then my answer is probably not of use.

Good luck!

Community
  • 1
  • 1
wageoghe
  • 27,390
  • 13
  • 88
  • 116
  • Thank you so much! Great tips! I ended up, before reading your ideas, implementing a very simple wrapper around log4net. It's just to simplify the statements each time i have to log something. It's pseudo-like: Logger.LogEntry(ILog, Message, Exception, Level[DEBUG|ERROR|WARNING|INFO], ...); whereas LogEntry always reads from the session and sets ThreadContext variables. It seems to work for my needs :) But now i have learnt something more and should try to implement your ideas to see if i can benefit from it more. //Daniel – Daniel Svensson Aug 17 '12 at 18:37