wcf - log4net 在 wcf PerSession 服务中使用 ThreadContext.Properties

标签 wcf log4net

我想在我的 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/

相关文章:

c# - WCF 循环引用序列化和堆栈溢出错误

javascript - 有用于 javascript 的 log4net 吗?

log4Net 配置转换

c# - Log4NET AdoNetAppender 连接字符串引用

c# - 如何以编程方式创建 BasicHttpBinding?

.net - WCF,发布 JSON 化数据

c# - Log4Net 自定义 AdoNetAppender 缓冲区问题

C# Log4Net - 以编程方式动态更改日志目录

c# - WCF 和 Ajax。不允许的方法让我发疯

c# - 处理 WCF header 详细信息