从代码中使用 XML 配置 log4net 或 NLog

发布于 2024-10-04 20:43:38 字数 765 浏览 3 评论 0原文

最近我一直在从事一个项目,除其他外,我们希望提供一个集中式配置系统。我们使用 WCF、Silverlight、C# 等来创建分布式服务和客户端系统。我们想要配置的事情之一是日志记录。显然,我们可以通过 app.config 或单独的日志配置文件来配置 log4net 或 NLog。我们也可以通过代码进行配置。我想看看是否可以通过代码通过 XML 进行配置。换句话说,假设您在内存中(可能是从数据库读取?)配置任一日志记录框架所需的整个 XML。能做到吗?是否可以通过包含正确形成的字符串(在特定日志框架的上下文中)来配置 log4net 和/或 NLog,而不是从文件中读取或通过“传统”API 配置?

我已经弄清楚如何为每个日志框架做到这一点。我不确定我们是否会真正使用它,但我想我会在这里分享它,以防万一其他人可能会发现它有用。另外,请随意评论以这种方式配置日志框架的建议(或不建议)。

我能想到的两个明显的潜在问题是:

  1. 构建有效的 XML(或将其输入数据库)可能很困难。我的第一个猜测是,人们会像今天一样定义 XML。将其放入 app.config(或外部配置)文件中,然后运行测试程序来验证 XML 是否产生预期结果。

  2. 更新数据库中的 XML 然后让程序/服务/任何内容对更改做出反应(例如使用 log4net 的 ConfigureAndWatch 选项)有多容易或困难(或不可能)?我对程序或服务如何知道 XML 已更新的机制不感兴趣。我们假设程序将定期检查数据库。给定一个新的 XML 字符串,重新配置日志框架是很容易的。

我将发布我的技术作为这个问题的答案。

Recently I have been working on a project where, among other things, we want to provide a centralized configuration system. We are using WCF, Silverlight, C#, etc to create a distributed system of services and clients. One of the things that we will want to configure is logging. Obviously, we can configure log4net or NLog via the app.config or via a separate logging configuration file. We can also configure via code. I wanted to see if it was possible to configure via XML from code. In other words, imagine that you have in memory (maybe read from a database?) the entire XML required to configure either logging framework. Can it be done? Is it possible to configure log4net and/or NLog via a string containing a correctly formed (in the context of the particular logging framework) as opposed to reading from the file or via "conventional" API configuration?

I have figured out how to do it for each of these logging frameworks. I'm not sure that we will actually use it, but I thought that I would share it here on SO, just in case anyone else might find it useful. Also, feel free to comment on the advisability (or not) of configuring the logging frameworks this way.

Two obvious potential issues that I can think of are:

  1. It could be difficult to construct valid XML (or enter it in the database). My first guess is that one would define the XML that same way one would today. Put it in a app.config (or external config) file and then run a test program to verify that the XML yields the expected results.

  2. How easy or difficult (or impossible) will it be to update the XML in the database and then have the program/service/whatever react to the change (like using log4net's ConfigureAndWatch option)? I am not as interested in the mechanics of how a program or service would know that the XML has been updated. Let's just assume that the program will check the database periodically. Given a new XML string, it is easy enough to reconfigure the logging frameworks.

I will post my technique as an answer to this question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青朷 2024-10-11 20:43:38

在代码中通过 XML 配置 log4net:

  string xml =
  @"<log4net>
    <appender name='file1' type='log4net.Appender.RollingFileAppender'>
      <!-- Log file locaation -->
      <param name='File' value='log4net.log'/>
      <param name='AppendToFile' value='true'/>
      <!-- Maximum size of a log file -->
      <maximumFileSize value='2KB'/>
      <!--Maximum number of log file -->
      <maxSizeRollBackups value='8'/>
      <!--Set rolling style of log file -->
      <param name='RollingStyle' value='Composite'/>
      <param name='StaticLogFileName' value='false'/>
      <param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <!-- Appender layout fix to view in console-->
    <appender name='console' type='log4net.Appender.ConsoleAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='Header' value='[Header]\r\n'/>
        <param name='Footer' value='[Footer]\r\n'/>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <appender name='debug' type='log4net.Appender.DebugAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
      </layout>
    </appender>
    <root>
      <level value='INFO'/>
      <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL 
            ERROR = 2 show  log -> FATAL ERROR 
            WARN =  3 show  log -> FATAL ERROR WARN 
            INFO =  4 show  log -> FATAL ERROR WARN INFO 
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->
      <!-- To write log in file -->
      <appender-ref ref='debug'/>
      <appender-ref ref='file1'/>
    </root>

  </log4net>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);

在代码中通过 XML 配置 NLog(适用于 NLog 2.0 及更高版本):

  string xml = @"<nlog> 
                   <targets> 
                     <target name='console' type='Console' layout='${message}' /> 
                   </targets> 

                   <rules> 
                     <logger name='*' minlevel='Error' writeTo='console' /> 
                   </rules> 
                 </nlog>"; 

  StringReader sr = new StringReader(xml); 
  XmlReader xr = XmlReader.Create(sr); 
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null); 
  LogManager.Configuration = config; 
  //NLog is now configured just as if the XML above had been in NLog.config or app.config

在 NLog 2.0 之前,NLog 的 XmlLoggingConfiguration 对象在其构造函数中不采用 XmlReader。您可以改为传递 XmlElement,如下所示:

  string xml = @"<nlog>  
               <targets>  
                 <target name='debugger' type='Console' layout='${message}' />  
               </targets>  

               <rules>  
                 <logger name='*' minlevel='Error' writeTo='console' />  
               </rules>  
             </nlog>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  XmlLoggingConfiguration config = new XmlLoggingConfiguration(doc.DocumentElement,null);
  LogManager.Configuration = config;

要更新配置(给定新的 XML 字符串),只需针对您正在使用的特定日志记录框架重复这些步骤即可。

Configure log4net via XML in code:

  string xml =
  @"<log4net>
    <appender name='file1' type='log4net.Appender.RollingFileAppender'>
      <!-- Log file locaation -->
      <param name='File' value='log4net.log'/>
      <param name='AppendToFile' value='true'/>
      <!-- Maximum size of a log file -->
      <maximumFileSize value='2KB'/>
      <!--Maximum number of log file -->
      <maxSizeRollBackups value='8'/>
      <!--Set rolling style of log file -->
      <param name='RollingStyle' value='Composite'/>
      <param name='StaticLogFileName' value='false'/>
      <param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <!-- Appender layout fix to view in console-->
    <appender name='console' type='log4net.Appender.ConsoleAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='Header' value='[Header]\r\n'/>
        <param name='Footer' value='[Footer]\r\n'/>
        <param name='ConversionPattern' value='%d [%t] %-5p  %m%n'/>
      </layout>
    </appender>

    <appender name='debug' type='log4net.Appender.DebugAppender'>
      <layout type='log4net.Layout.PatternLayout'>
        <param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
      </layout>
    </appender>
    <root>
      <level value='INFO'/>
      <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL 
            ERROR = 2 show  log -> FATAL ERROR 
            WARN =  3 show  log -> FATAL ERROR WARN 
            INFO =  4 show  log -> FATAL ERROR WARN INFO 
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->
      <!-- To write log in file -->
      <appender-ref ref='debug'/>
      <appender-ref ref='file1'/>
    </root>

  </log4net>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);

Configure NLog via XML in code (works for NLog 2.0 and later):

  string xml = @"<nlog> 
                   <targets> 
                     <target name='console' type='Console' layout='${message}' /> 
                   </targets> 

                   <rules> 
                     <logger name='*' minlevel='Error' writeTo='console' /> 
                   </rules> 
                 </nlog>"; 

  StringReader sr = new StringReader(xml); 
  XmlReader xr = XmlReader.Create(sr); 
  XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null); 
  LogManager.Configuration = config; 
  //NLog is now configured just as if the XML above had been in NLog.config or app.config

Prior to NLog 2.0, NLog's XmlLoggingConfiguration object does not take an XmlReader in its constructor. You can pass an XmlElement instead, like this:

  string xml = @"<nlog>  
               <targets>  
                 <target name='debugger' type='Console' layout='${message}' />  
               </targets>  

               <rules>  
                 <logger name='*' minlevel='Error' writeTo='console' />  
               </rules>  
             </nlog>";

  XmlDocument doc = new XmlDocument();
  doc.LoadXml(xml);

  XmlLoggingConfiguration config = new XmlLoggingConfiguration(doc.DocumentElement,null);
  LogManager.Configuration = config;

To update the configuration, given a new XML string, simply repeat the steps for the particular logging framework that you are using.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文