EntLib5.0 日誌應用程式塊(logging) 使用與配置

來源:互聯網
上載者:User
1.Logging Block的基礎概念

EntLib 5.0 的日誌組件單獨使用比log4net,common.Logging等似乎要麻煩很多,而且要顯式引用

Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.Logging
Microsoft.Practices.ServiceLocation
等三個dll檔案,實際上Microsoft.Practices.ServiceLocation,還需要引用
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll
這兩個程式集。不過如果你已經使用其他應用程式塊如Unity,乾脆就做全套了,使用Logging Block做日誌記錄組件。

logging block的主要概念如:

LogWriter 是一個抽象類別,可以使用EnterpriseLibraryContainer.Current.GetInstance<LogWriter>()建立立,

EnterpriseLibraryContainer在Microsoft.Practices.EnterpriseLibrary.Common.Configuration命名空間下,

也可以使用var logWriter= (new LogWriterFactory()).Create();建立,本質都是使用Unity容器建立對象,而且使用了單例模式,因此不管調用多少次
EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();返回的多是同個LogWriter執行個體.

LogFilter 是一組可配置的全域過濾器,比方Log Enabled Filter 的Enabled設定成False那麼將不記錄任何日誌.

Trace Source 在設定檔與代碼中體現為Category,是對日誌實體(LogEntry)的一個分類,一個日誌(a logEntry)可以被指派給多個Category(預設是Genearl Category),而一個Category對應一個Trace Source,一個Trace Source 之所以叫Source是相對Trace Listener來說,LogWriter將沒有被LogFilter過濾掉的logEntry按Category發送給一個或多個指定的Trace Source後就完事了,剩下的就是以Trace Source為起點,將logEntry發給一個或多個Trace Listener的處理過程,Trace Source可以說是一個廣播站,裡面儲存了一個來自應用系統各處送來的符合該廣播站category要求的logEntry稿件,而該廣播站維護著一個 Trace Listerner (收聽者)列表,它會將每個logEntry資訊複製一分給發給每個Trace Listener。

Trace Listener 具體執行將logEntry記錄到Database, 文字檔,Windows日誌,MSMQ等目標儲存中。在以前的Ent Lib版本裡叫通道(sink)

Log Formatter  對logEntry進行格式化輸出有一組可配置的站位符,一個 Trace Listener 可以指定零個或多個Log Formatter

總的來說一個 Trace Source 配置對應多個 Trace Listener配置 ,而一個Trace Listener配置可以被多個Trace Source配置引用,同樣的多對多關係也存在於Trace Listener與Log Formatter配置之間,當然其內參對象可能的存在是,根據配置只產生對應配置個數的Trace Source,TraceListener,根據Category中的配置建立參考關聯性,當TraceListener監聽到有logEntry到達TraceSource時則將logEntry擷取過來加到自己的logEntry隊列裡,在合適的情況下寫到目標儲存中

2.Windows日誌與文本Trace Listener

Event Log Trace Listener

將日誌寫到Windows日誌中,需要指定Source Name屬性,預設是寫到"應用程式"日誌中,

可以使用System.Diagnostics.EventLog.CreateEventSource("XXX系統", "XXX系統");

建立一個獨立的Window記錄檔與來源記錄日誌.

參考:

Rolling Flat File Trace Listener

滾動平板檔案,一般使用文字檔(*.txt)

Property

Description

File Name

This is the name of the rolling flat file. This is a required value. It can include environment variables such as %WINDIR%, %TEMP%, and %USERPROFILE%. If you also set the Max Archived Files property, See the advice on choosing a file name in the following Remarks section.
記錄檔名,可以帶%windir%這樣的環境變數,可以包括目錄路徑

Severity Filter

Applies a filter that selects the level of message that it will detect. The valid values are All (the default), Off, Critical, Error, Warning, Information, Verbose, and ActivityTracing. The setting effectively means "the specified level and everything more important." For example, the Warning setting will detect warnings, errors, and critical events.

Message Footer

Additional information contained in the file footer. The default is "----------------------------------------." This is optional.

Formatter Name

The formatter to use with this trace listener. Select one from the drop-down list. The default is none. This is optional.
要使用的格式化器的名字引用

Message Header

Additional information contained in the file header. The default is "----------------------------------------." This is optional.

Max Archived Files

The maximum number of log files to retain. When set to an integer value, the trace listener will purge old files based on the file creation date when the number exceeds the specified value. See the note in the following Remarks section if you set this property.
目錄下最多允許的記錄檔個數,當檔案數超過這個數時,早先建立的檔案將被刪除最後留下不超過Max Archived Files個數的檔案,刪除按[file-name] *.file-extension進行匹配

Name

This is the name of the trace listener. The default is Rolling Flat File Trace Listener. This is required.

File Exists Behavior

This property determines what occurs to an existing file when it rolls over. If you select Increment, the application block creates a new file and names it by incrementing the timestamp. If you select Overwrite and do not provide a value for the Timestamp Pattern property, the existing file is overwritten.
當滾動行為被觸發時,是建立一個新檔案還是覆蓋原來的檔案(刪除後建立個同名檔案)

Roll Interval

This property determines when the log file rolls over. You can select None (the default), Midnight (in which case the log will roll over at midnight), Minute, Hour, Day, Month, Week, or Year. This is optional.
按時間間隔觸發滾動行為,具體的滾動行為在File Exists Behavior屬性設定

Roll Size KB

This is the maximum size the file can reach, in kilobytes, before it rolls over. This is optional.
按檔案大小觸發滾動行為,可以跟Roll Interval合用,合用時在兩個條件多滿足時觸發滾動行為

Timestamp Pattern

This is the date/time format that is appended to the new file name (see the Remarks section that follows this table).
建立記錄檔時將做為檔案名稱的一部分,使用時間格式化字串設定如yyyy-MM-dd

Trace Output Options

Trace listeners that do not output to a text formatter use this property to determine which options, or elements, should be included in the trace output. Possible values are: CallStack, DateTime, LogicalOperationStack, None, ProcessId, ThreadId, and Timestamp. The default is None. For an explanation of these values, see TraceOutputOptions Values. This is optional.
改屬性只有在Formatter Name設定為空白時才將屬性設定值對應內容輸出到日誌中


注意
  • 如果設定了Max Archived Files屬性,當前Trace listener 將清理全部(配置的日誌儲存目錄)檔案名稱符合 [file-name]*.file-extension規則的檔案,因此,其他Trace Listener 如果也將記錄檔輸出到這個目錄並且檔案名稱也符合這個規則的將被誤刪,為了避免這個情況需要將File Name 屬性按不同Trace listener 設定成 [file-name].[additional-name].file-extension的形式。 
  • 可以按檔案大小或檔案年齡(建立時間)或兩個條件的“與”組合來控制檔案的滾動行為的觸發。
  • 如果選擇Increment作為File Exists Behavior的屬性,那麼當記錄檔達到滾動點時,日誌應用程式塊將建立一個新的檔案,檔案名稱是 FileName屬性的檔案名稱(不包括副檔名與路徑)+TimestampPattern+[整數+] FileName屬性指定的副檔名 
  • 如果選擇Overwrite作為File Exists Behavior的屬性,當記錄檔達到滾動點時,應用程式塊將建立一個新的同名檔案來替換原來存在的檔案,如果你同時也設定了Timestamp Pattern屬性,那麼新建立的檔案將按,"FileName屬性的檔案名稱(不包括副檔名與路徑)+TimestampPattern+FileName屬性指定的副檔名"方式命名,如果目錄不存在同名的檔案,那麼目錄下將新增這個檔案,如果目錄已經存在這個同名檔案那麼應用程式塊將先嘗試刪除再建立,如果無法刪除(檔案可能被鎖定了)那麼應用程式塊將採用Increment方式建立新檔案。另外當Time stamp Pattern是 yyyy-MM-dd時,每天至少會新增一記錄檔。
  • FileName屬性如果使用的是相對路徑,那麼相對路徑解析時的基準路徑是AppDomain.CurrentDomain.BaseDirectory. 比方設定File Name="log/log.txt", WinForm Console形式的程式將在可執行檔所在的目錄建立一個log檔案夾,log.txt檔案將儲存在log檔案夾下(調試時將在bin/Debug/目錄裡), 而Aspx程式將在根目錄下(跟web.config同個目錄)建立立一個log檔案夾.
3.具體配置

配置時先用EntLib5.0提供的圖形組態工具產生xml配置文本,然後Copy到App.config或Web.config中

1.添加引用

2.配置Web.config

        <!-- EntLib5.0 Loggin -->
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>

3.配置logging.config

  <loggingConfiguration  name="" tracingEnabled="true" defaultCategory="General">
    <listeners>
      <add name="Event Log Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          source="XXX系統" formatter="Text Formatter" />
      <add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          fileName="log/log.txt" formatter="Text Formatter" rollFileExistsBehavior="Increment"
          rollSizeKB="500" />
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
          name="Text Formatter" />
    </formatters>
    <logFilters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          enabled="true" name="Logging Enabled Filter" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          name="Priority Filter" />
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
          name="Category Filter" />
    </logFilters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Rolling Flat File Trace Listener" />
        </listeners>
      </add>
      <add switchValue="All" name="Trace">
        <listeners>
          <add name="Rolling Flat File Trace Listener" />
        </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="Event Log Trace Listener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>

4.目錄結構

=============相關代碼===============

下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.