Best practice to include log4Net external config file in ASP.NET

匿名 (未验证) 提交于 2019-12-03 02:04:01

问题:

I have seen at least two ways to include an external log4net config file in an ASP.NET web application:

Having the following attribute in your AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log.config", Watch = true)] 

Calling the XmlConfigurator in the Global.asax.cs:

protected void Application_Start() {     XmlConfigurator.Configure(new FileInfo("Log.config")); } 

What would be the best practice to do it?

回答1:

At startup, call:

XmlConfigurator.Configure(); 

In your Web.config, specify log4net.Config in appSettings:

This special setting allows you to change the log configuration without having to recompile. Especially helpful for moving between multiple environments.

Example

Consider the following project file structure:

\config\log4net\debug.config \config\log4net\staging.config \config\log4net\release.config \config\appSettings\debug.config \config\appSettings\staging.config \config\appSettings\release.config 

Application and logging configurations are distinguished for each environment. References to the logging configurations are maintained in the application settings.

\config\appSettings\debug.config:

     ... 

\config\appSettings\staging.config:

     ... 

\config\appSettings\release.config:

     ... 

Changing environments is a simple matter of updating the appSettings file in Web.config.

     ... 


回答2:

I was dissatisfied with the "magic" configuration approach, because I wanted to specify my configuration in a path with an environment variable (%PUBLIC%\MyApp\MySettings.config).

So instead, I have this in my app.config:

And do this to set my log4net configuration:

var configFile = ConfigurationManager.AppSettings.Get("MyLog4NetConfigFile"); if( !string.IsNullOrEmpty(configFile)) {     configFile = Environment.ExpandEnvironmentVariables(configFile);     XmlConfigurator.Configure(new FileInfo(configFile)); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!