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="C#" Debug="true" Service="Test.CustomService" CodeBehind=“Test.CustomService.svc.cs”>中加入
//Factory=“Test.CustomServiceHostFactory”
//即<%@ ServiceHost Language="C#" Debug="true" Service="Test.CustomService" Factory=“Test.CustomServiceHostFactory” CodeBehind=“Test.CustomService.svc.cs”>
//再次部署後,第一次調用IIS上的WCF服務也可以自動啓動記錄日誌了