我可以在运行时更改企业库日志记录块的配置吗?

Ori*_*rds 2 logging enterprise-library configuration-files

在没有深入讨论EntLib日志块的优点或其他内容的情况下,有什么方法可以在运行时更改它的配置?

例如,我将块配置为将常规事件记录到平面文件,将重要事件记录到事件日志.
是否有任何方法可以更改它以将常规事件记录到控制台等,而无需重新启动我的应用程序?

澄清:我正在编写一个长期运行的服务器应用程序.我希望能够临时增加各种日志记录组的详细程度/输出以进行诊断/故障排除,而无需重新启动应用程序.重启不是一种选择,因为它意味着生产中的"站点停机".

Jak*_*ade 5

它实际上很容易实现,只需按照以下步骤操作:

将Enterprise Library配置放在单独的文件中

<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>
Run Code Online (Sandbox Code Playgroud)

添加日志记录筛选器.您可以使用日志条目优先级或类别来过滤日志条目,因此在代码中应相应地设置优先级或类别.例如,您希望提供非常重要的消息和低优先级编号,例如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>
Run Code Online (Sandbox Code Playgroud)

在运行时对Enterprise Library配置所做的任何更改都将被忽略 - 除了对Logging Application Block所做的更改.在MSDN上查看此文章:在运行时更新配置设置

我实现了一个简单的帮助方法来切换过滤器值:当我想要更详细的消息时,我允许通过增加最大优先级值来注册这些条目.同样,当我只想记录异常或其他非常重要的消息时,我将优先级范围设置为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);
Run Code Online (Sandbox Code Playgroud)

这将更改企业库日志记录功能,而无需重新加载您的服务,因为永远不会触及web.config.唯一的缺点是需要使用soem类型的日志条目优先级/分类约定.