c#.. Net:如何通过.Net代码读取App.config中定义的跟踪文件路径

本文关键字:Net 定义 文件 路径 config 跟踪 App 何通过 代码 读取 | 更新日期: 2023-09-27 18:12:44

在App.Config中跟踪文件路径-

<loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
      <listeners>
         <add fileName="D:'trace.log" header="----------------------------------------" footer="----------------------------------------" formatter="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="FileTraceListener" />
      </listeners>
      <formatters>
         <add template="Timestamp: {timestamp}{newline} Message: {message}{newline} Category: {category}{newline} Priority: {priority}{newline} EventId: {eventid}{newline} Severity: {severity}{newline} Title:{title}{newline} Machine: {localMachine}{newline} App Domain: {localAppDomain}{newline} ProcessId: {localProcessId}{newline} Process Name: {localProcessName}{newline} Thread Name: {threadName}{newline} Win32 ThreadId:{win32ThreadId}{newline} Extended Properties: {dictionary({key} - {value}{newline})}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Text Formatter" />
      </formatters>
      <categorySources>
         <add switchValue="All" name="General">
            <listeners>
               <add name="FileTraceListener" />
            </listeners>
         </add>      
      </categorySources>
      <specialSources>
         <allEvents switchValue="All" name="All Events" />
         <notProcessed switchValue="All" name="Unprocessed Category" />
         <errors switchValue="All" name="Logging Errors &amp; Warnings">
            <listeners>
               <add name="FileTraceListener" />
            </listeners>
         </errors>
      </specialSources>
</loggingConfiguration>
这里我们定义了一个监听器,即FileTraceListener。请帮助我得到以下答案-
  1. 如何访问跟踪路径?
  2. 如何将细节写入跟踪文件?

c#.. Net:如何通过.Net代码读取App.config中定义的跟踪文件路径

您正在使用Enterprise Library Logging,因此要获得第一个记录器,您将使用以下代码:

LoggingSettings loggingSettings = (LoggingSettings)ConfigurationManager.GetSection(LoggingSettings.SectionName);
TraceListenerData traceListenerData = loggingSettings.TraceListeners.Get(0);
FlatFileTraceListenerData objFlatFileTraceListenerData = traceListenerData as FlatFileTraceListenerData;
string logFilePath = objFlatFileTraceListenerData.FileName; 

注意:如果您想获得一个特定的监听器替换Get(0)Get("FlatFile TraceListener");