I'm using PostSharp with the TraceAttribute
on each class in order to write to log files. A new requirement is to be able to prepend each log entry with the SessionID
.
PostSharp doesn't seem to be able to work this way though. I've tried the two approaches that made sense to me and neither work.
Try #1
I added a string parameter to the TraceAttribute
constructor to be passed in and used by the OnEntry
, OnExit
and OnException
methods.
private readonly string _sessionID;
public TraceAttribute(string sessionID)
{
_sessionID = sessionID;
logger = new Logger();
}
public override void OnExit(MethodExecutionArgs args)
{
logger.LogMethodExit(string.Format("Session {0} Exiting {1}.{2}", _sessionID, args.Method.DeclaringType.FullName, args.Method.Name));
}
My controllers were decorated with the [Trace] attribute originally and I modified to this approach...
[Trace(HttpContext.Session.SessionID)]
This doesn't work as the HttpContext
is not available in a static context.
So that idea is out the window.
Try #2
So my next try was to simply create the sessionId
variable locally to each method in the TraceAttribute
...
public override void OnEntry(MethodExecutionArgs args)
{
var sessionID = HttpContext.Current.Session.SessionID;
logger.LogMethodEntry(string.Format("Session {0} Entering {1}.{2}", sessionID, args.Method.DeclaringType.FullName, args.Method.Name));
}
This doesn't work either as again, the HttpContext
is not yet available and is a null
object at runtime as soon I run the solution..
Try #3
public override void OnEntry(MethodExecutionArgs args)
{
string sessionID = "Not initialized";
if (HttpContext.Current.Session.SessionID != null)
sessionID = HttpContext.Current.Session.SessionID;
logger.LogMethodEntry(string.Format("Session {0} Entering {1}.{2}", sessionID, args.Method.DeclaringType.FullName, args.Method.Name));
}
Is there any way to get the session information into a TraceAttribute
that is weaved with PostSharp in this manner? Some workaround that can accomplish this goal?