开发者

Correctly use <system.diagnostics> settings in application configuration file

开发者 https://www.devze.com 2023-01-20 13:05 出处:网络
I recently created a Windows service. One thing that it faithfully does is log any errors to the Application log. I have the following code that does this:

I recently created a Windows service. One thing that it faithfully does is log any errors to the Application log. I have the following code that does this:

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

I also have the following in my app.config:

<system.diagnostics>
    <sources>
      <source name="MyServ开发者_高级运维ice" 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>

I would expect that my code above should work even without setting the Source property of EventLog programmatically because I've already defined the source in the config file. But if I remove With {.Source = "MyService"}, then I get an Exception, which that says that the Source property should be set before calling WriteEntry method. So, what's purpose of the stuff in the configuration XML?


As luck has it, I've stumbled on an answer, or at least a partial one while working on a different app. The settings in the config file matter when using My.Application.Log object. For example: My.Application.Log.WriteEntry(errMsg) will write to a file or to the Event Viewer depending on the setting in app.config.

So, in this case, the EventLog class is not called directly from code. This gives me the extra flexibility to "hot-swap" the log format from Event Viewer to file, for example, without changing any code or recompiling. One thing that I did notice though is that the Name property of the <source> element needs to be set to "DefaultSource". Otherwise, events don't get logged. There's probably a way to change that, but I didn't see a need, so I didn't investigate further. Hopefully, this will be useful to somebody.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号