博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

EntLib5.0 日志应用程序块(logging) 使用与配置

Posted on 2012-01-04 11:22  ☆Keep★Moving☆  阅读(403)  评论(0编辑  收藏  举报

來源 http://www.cnblogs.com/wdfrog/archive/2011/06/13/2078338.html

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.目录结构

=============相关代码===============

下载