WCF部署到IIS上之後log4net不記錄日誌的解決方案
阿新 • • 發佈:2019-02-13
問題及環境:在web專案中直接新增的wcf服務。web專案中增加Global.asax,在Global.asax的Application_Start事件中註冊log4net
部署到IIS之後,WCF服務正常執行。w3wp在第一次呼叫時也已經啟動。但是,所有的日誌都沒有。
//然後,右鍵CustomService.svc檔案-檢視標記
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服務也可以自動啟動記錄日誌了