log4net using ThreadContext.Properties in wcf PerSession service

前端 未结 2 1655
情深已故
情深已故 2021-01-19 02:03

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.Login         


        
2条回答
  •  无人共我
    2021-01-19 02:47

    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;
       }
    }
    

提交回复
热议问题