【问题标题】:Correctly use <system.diagnostics> settings in application configuration file正确使用应用程序配置文件中的 <system.diagnostics> 设置
【发布时间】:2010-10-15 20:46:58
【问题描述】:

我最近创建了一个 Windows 服务。它忠实地做的一件事是将任何错误记录到应用程序日志中。我有以下代码:

Dim appLog = New System.Diagnostics.EventLog With {.Source = "MyService"}
appLog.WriteEntry(message, EventLogEntryType.Error, transactionID)

我的 app.config 中还有以下内容:

<system.diagnostics>
    <sources>
      <source name="MyService" switchName="DefaultSwitch">
        <listeners>
          <!--<add name="FileLog"/>-->          
          <add name="EventLog"/>
        </listeners>
      </source>
    </sources>
    <switches>
      <add name="DefaultSwitch" value="Information" />
    </switches>
    <sharedListeners>
      <!--<add name="FileLog"
           type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
           initializeData="FileLogWriter"/>-->      
      <add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="MyService"/> 
    </sharedListeners>
  </system.diagnostics>

我希望上面的代码即使没有以编程方式设置 EventLog 的 Source 属性也应该可以工作,因为我已经在配置文件中定义了源。但是如果我删除With {.Source = "MyService"},那么我会得到一个异常,它表示应该在调用 WriteEntry 方法之前设置 Source 属性。那么,配置 XML 中的东西的用途是什么?

【问题讨论】:

    标签: .net configuration windows-services event-log


    【解决方案1】:

    幸运的是,我在开发不同的应用程序时偶然发现了一个答案,或者至少是部分答案。使用 My.Application.Log 对象时,配置文件中的设置很重要。例如:My.Application.Log.WriteEntry(errMsg) 将写入文件或事件查看器,具体取决于 app.config 中的设置。

    因此,在这种情况下,EventLog 类不会直接从代码中调用。这给了我额外的灵活性,可以将日志格式从事件查看器“热交换”到文件,例如,无需更改任何代码或重新编译。我确实注意到的一件事是 &lt;source&gt; 元素的 Name 属性需要设置为“DefaultSource”。否则,不会记录事件。可能有一种方法可以改变它,但我没有看到有必要,所以我没有进一步调查。希望这对某人有用。

    【讨论】:

      猜你喜欢
      • 2010-12-14
      • 2010-10-01
      • 1970-01-01
      • 2021-02-05
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多