使用带有 TraceAttribute 的 PostSharp 以使用 HttpContext 的 SessionID 进行日志记录 [英] Using PostSharp with TraceAttribute for logging with HttpContext's SessionID
问题描述
我在每个类上使用带有 TraceAttribute
的 PostSharp 以写入日志文件.一个新的要求是能够在每个日志条目前面加上 SessionID
.
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 似乎无法以这种方式工作.我尝试了两种对我有意义的方法,但都不起作用.
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.
尝试 #1
我向 TraceAttribute
构造函数添加了一个字符串参数,以供 OnEntry
、OnExit
和 OnException<传入和使用/code> 方法.
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));
}
我的控制器最初是用 [Trace] 属性装饰的,我修改了这种方法......
My controllers were decorated with the [Trace] attribute originally and I modified to this approach...
[Trace(HttpContext.Session.SessionID)]
这不起作用,因为 HttpContext
在静态上下文中不可用.
This doesn't work as the HttpContext
is not available in a static context.
所以这个想法是不可能的.
So that idea is out the window.
尝试#2
所以我的下一个尝试是简单地为 TraceAttribute
...
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));
}
这也不起作用,HttpContext
尚不可用,并且在我运行解决方案后在运行时是一个 null
对象..
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..
尝试 #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));
}
有什么办法可以将会话信息放入一个以这种方式用 PostSharp 编织的 TraceAttribute
中?一些可以实现此目标的解决方法?
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?
推荐答案
成功了,我错过了在 web.config 中提交的会话.
Got it working, I was missing my session being turned in in web.config.
将此行添加到配置中,现在可以正常工作了.
Added this line to config and it works fine now.
<sessionState mode="InProc" cookieless="false" timeout="20"/>
这篇关于使用带有 TraceAttribute 的 PostSharp 以使用 HttpContext 的 SessionID 进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!