Dot-Net

如何在配置文件中控制跟踪偵聽器的級別

  • September 13, 2010

我正在嘗試學習跟踪的內置功能。我不知道如何使用配置來設置寫入我聽的級別(資訊、警告、錯誤)。

我有預設的 app.config 。在我的程式碼中,我使用 Trace.TraceInformation() 和 Trace.TraceError。

所有消息都寫入我的文本文件。我希望能夠更改 app.config 中的某些內容以使其記錄資訊消息或僅記錄錯誤消息。

模組1.vb

Sub Main(ByVal args() As String)
   Dim index As Integer = 0
   For Each arg As String In args
       Trace.TraceInformation(String.Format("Sub Main(): arg({1}) = {0}", arg, index))
       Trace.Flush()

       If arg.Split("=").Count = 2 Then
           If String.Compare(arg.Split("=")(0), "mode", True) = 0 Then _Mode = arg.Split("=")(1)
       End If

       index += 1
   Next
End Sub

應用程序配置

   <sources>
       <!-- This section defines the logging configuration for My.Application.Log -->
       <source name="DefaultSource">
           <listeners>
               <add name="FileLog"/>
               <!-- Uncomment the below section to write to the Application Event Log -->
               <!--<add name="EventLog"/>-->
           </listeners>
       </source>
   </sources>
   <switches>
       <add name="DefaultSwitch" value="1" />

   </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"/>
       <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
       <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="HealthSurvey Console"/> -->
   </sharedListeners>

</system.diagnostics>

我不喜歡回答你自己的問題,但我也不喜歡在沒有將某些內容標記為答案的情況下留下問題。當我找到我要找的東西時尤其如此。

這個連結有我需要的資訊。我會總結一下,因為它很長。在配置中,您添加一個偵聽器。我需要的關鍵是使用<filter>監聽器。有了它,我可以部署我的應用程序,然後更改配置以控制寫入文件的文本。我可以添加另一個具有不同過濾器的偵聽器,例如事件日誌。

不管怎樣,關鍵是<filter>。該屬性initializeData設置為來自 System.Diagnostics.SourceLevels枚舉的文本。

  • 資訊允許資訊、警告和錯誤
  • 警告允許警告和錯誤
  • 錯誤只允許錯誤

應用程序配置

<system.diagnostics>
 <trace autoflush="false" indentsize="1">
   <listeners>
     <add name="textListener"
          type="System.Diagnostics.TextWriterTraceListener"
          traceOutputOptions="None"
          initializeData="C:\Projects\TraceLogOutput.log">
       <filter 
          type="System.Diagnostics.EventTypeFilter"
          initializeData="Information"/>
     </add>
   <remove name="Default" />
 </listeners>
</trace>

模組1.vb

Sub Main(ByVal args() As String)

   ' initializeData = Information only
   Trace.TraceInformation("Some Information message")
   Trace.Flush()

   ' initializeData = Information or Warning
   Trace.TraceWarning("Some Warning message")
   Trace.Flush()

   ' initializeData = Information, Warning or Error
   Trace.TraceError("Some Error message")
   Trace.Flush()

End Sub

引用自:https://stackoverflow.com/questions/3704907