在不讨论 EntLib 日志记录 block 的优点或其他方面的情况下,有什么方法可以在运行时更改它的配置?
例如,我将 block 配置为将一般事件记录到平面文件,将关键事件记录到事件日志。
有什么方法可以更改它以将常规事件记录到控制台等,而无需重新启动我的应用程序?
说明:我正在编写一个长时间运行的服务器应用程序。我希望能够在不重新启动应用程序的情况下临时增加各种日志记录组的详细程度/输出以用于诊断/故障排除目的。重启不是一种选择,因为这意味着生产中的“站点停机”。
最佳答案
其实很容易实现,只需按照以下步骤操作即可:
将企业库配置放在一个单独的文件中
<configuration>
<configSections>
<section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<enterpriseLibrary.ConfigurationSource selectedSource="EntLib Config">
<sources>
<add name="EntLig Config" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
filePath="EntLib.config" />
</sources>
</enterpriseLibrary.ConfigurationSource>
</configuration>
添加日志过滤器。您可以使用日志条目优先级或类别来过滤日志条目,因此在您的代码中您应该相应地设置优先级或类别。例如,你想给非常重要的消息和低优先级的数字,比如 1,更详细的消息可以是 10。
<configuration>
...
<loggingConfiguration name="Logging Application Block" tracingEnabled="true"
defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
...
<logFilters>
<add minimumPriority="1" maximumPriority="10" type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Priority Filter" />
...
</loggingConfiguration>
</configuration>
在运行时对企业库配置所做的任何更改都将被忽略——除了对日志应用程序 block 所做的更改。请参阅 MSDN 上的这篇文章:Updating Configuration Settings at Run-time
我实现了一个简单的辅助方法来切换过滤器值:当我想要更详细的消息时,我允许通过增加最大优先级值来注册这些条目。同样,当我只想记录异常或其他非常重要的消息时,我将优先级范围设置为 0 到 1。
var path = System.IO.Path.Combine(Environment.CurrentDirectory, "EntLib.config");
var xd = XDocument.Load(path);
var x = (from z in xd.Root.Elements("loggingConfiguration").Elements("logFilters").Elements() where (z.Attribute("name").Value == "Priority Filter") select z).SingleOrDefault();
x.Attribute("minimumPriority").Value = 1; // Change this value...
x.Attribute("maximumPriority").Value = 5; // ... and this one to specify the range you want to log.
xd.Save(path);
这将更改企业库日志记录功能,而无需重新加载您的服务,因为永远不会触及 web.config。唯一的缺点是它需要您使用某种约定来对日志条目进行优先级排序/分类。
关于logging - 我可以在运行时更改 Enterprise Library Logging block 的配置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/624436/