wcf PerSession服务中使用ThreadContext.Properties的log4net

Col*_*e W 5 wcf log4net

我想在wcf服务中使用以下命令在日志消息中记录用户:

log4net.ThreadContext.Properties["user"] = this.currentUser.LoginName;
Run Code Online (Sandbox Code Playgroud)

我已设置要在中运行的服务InstanceContextMode.PerSession。在对wcf服务的初始调用中,我将此ThreadContext属性设置为已登录的当前用户,但随后的每次调用都不会记录此属性。

我非常确定,即使将其设置为use,对于服务的每次调用也会在不同的线程上运行任务PerSession。我假设它正在使用线程池来处理请求。

有没有一种方法可以设置这个,这样我就不必在每个wcf方法中都这样做?

Ale*_*Dev 2

我遇到了同样的问题,这就是我让它工作的方法。您可以使用 GlobalContext,因为无论如何都会对每次调用进行评估。

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
    //static constructor
    static MyService()
    {
        log4net.Config.XmlConfigurator.Configure();
        log4net.GlobalContext.Properties["user"] = new UserLogHelper();
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后你必须定义一个简单的类:

private class UserLogHelper
{
    public override string ToString()
    {
        var instanceContext = OperationContext.Current.InstanceContext;
        var myServiceInstance = instanceContext.GetServiceInstance() as MyService;
        return myServiceInstance?.currentUser?.LoginName;
   }
}
Run Code Online (Sandbox Code Playgroud)