wcf PerSession服务中使用ThreadContext.Properties的log4net [英] log4net using ThreadContext.Properties in wcf PerSession service

查看:114
本文介绍了wcf PerSession服务中使用ThreadContext.Properties的log4net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use the following in my wcf service to log the user in the log message:

log4net.ThreadContext.Properties["user"] = this.currentUser.LoginName;

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

I have the service set up to run in InstanceContextMode.PerSession. In the initial call to the wcf service I am setting this ThreadContext property to the current user that is logged in but each subsequent call does not log this property.

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

I'm pretty sure that for each call to the service it's running the task on a different thread even though it's set to use PerSession. I assume it's using a thread pool to process the requests.

推荐答案

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

I ran into the same problem and this is how I got it to work. You can use GlobalContext since it will be evaluated for each call anyway.

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

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

Then you have to define a simple class:

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

这篇关于wcf PerSession服务中使用ThreadContext.Properties的log4net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆