超酷小 发表于 2015-11-15 09:12:47

WCF部署到IIS上之后log4net不记录日志的解决方案

问题及环境:在web项目中直接添加的wcf服务。web项目中增加Global.asax,在Global.asax的Application_Start事件中注册log4net  
  
  

protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}

部署到IIS之后,WCF服务正常运行。w3wp在第一次调用时也已经启动。但是,所有的日志都没有。  
  于是,在IIS上浏览svc文件。再调用WCF服务时日志正常。

Application_Start在直接调用的时候并没有被执行,只有在浏览svc页面时才被执行了。  
  


  所以在global中注册log4net只能靠运维部署时来浏览svc来启动日志。
  


  怎么解决呢?
  使用自定义ServiceHost
  默认的IIS宿主只能创建ServiceHost实例 ,所以在自定义的ServiceHost实例中来注册log4net启动日志记录是最好的选择了。
  如下,自定义一个ServiceHost的子类
  一个ServiceHostFactory的子类
  

using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace Test
{
public class CustomServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(
Type serviceType, Uri[] baseAddresses)
{
CustomServiceHost customServiceHost =
new CustomServiceHost(serviceType, baseAddresses);
return customServiceHost;
}
}
public class CustomServiceHost : ServiceHost
{
public CustomServiceHost(Type serviceType, params Uri[]baseAddresses)
: base(serviceType, baseAddresses)
{
log4net.Config.XmlConfigurator.Configure();
}
protected override void ApplyConfiguration() {
base.ApplyConfiguration();
}
}
}



//然后,右键CustomService.svc文件-查看标记  //在<%@ ServiceHost Language=&quot;C#&quot; Debug=&quot;true&quot; Service=&quot;Test.CustomService&quot; CodeBehind=“Test.CustomService.svc.cs”>中加入
  //Factory=“Test.CustomServiceHostFactory”
  //即<%@ ServiceHost Language=&quot;C#&quot; Debug=&quot;true&quot; Service=&quot;Test.CustomService&quot; Factory=“Test.CustomServiceHostFactory” CodeBehind=“Test.CustomService.svc.cs”>
  //再次部署后,第一次调用IIS上的WCF服务也可以自动启动记录日志了
  
  
  


         
版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: WCF部署到IIS上之后log4net不记录日志的解决方案