我想在我的 wcf 服务中使用以下内容在日志消息中记录用户:
log4net.ThreadContext.Properties["user"] = this.currentUser.LoginName;
我已将服务设置为在
InstanceContextMode.PerSession
中运行.在对 wcf 服务的初始调用中,我设置了这个 ThreadContext
属性分配给当前登录的用户,但每次后续调用都不会记录此属性。我很确定每次调用服务时它都会在不同的线程上运行任务,即使它设置为使用
PerSession
.我假设它使用线程池来处理请求。有没有办法设置它,这样我就不必在每个 wcf 方法中都这样做?
最佳答案
我遇到了同样的问题,这就是我让它工作的方式。您可以使用 GlobalContext,因为无论如何都会为每次调用评估它。
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
//static constructor
static MyService()
{
log4net.Config.XmlConfigurator.Configure();
log4net.GlobalContext.Properties["user"] = new UserLogHelper();
}
...
}
然后你必须定义一个简单的类:
private class UserLogHelper
{
public override string ToString()
{
var instanceContext = OperationContext.Current.InstanceContext;
var myServiceInstance = instanceContext.GetServiceInstance() as MyService;
return myServiceInstance?.currentUser?.LoginName;
}
}
关于wcf - log4net 在 wcf PerSession 服务中使用 ThreadContext.Properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9047889/