Log4Net 手册

  首先感慨下,现在的程序员做的工作因为高级语言的生产力,系统框架模式的成熟,开源大牛的贡献,已经成越来越偏向 “面向配置编程”了......

详细使用指南见文章:http://blog.csdn.net/zhoufoxcn/article/details/2220533

1.Log4net的结构

  1.1 Logger

    Logger是应用程序需要交互的主要组件,它用来产生日志消息。产生的日志消息并不直接显示,还要预先经过Layout的格式化处理后才会输出。Log4net框架定义了一个ILog接口,所有的logger类都必须实现这个接口。如果你想实现一个自定义的logger,你必须首先实现这个接口,ILog定义如下:

public interface ILog 

{ 

  void Debug(object message); 

  void Info(object message); 

  void Warn(object message); 

  void Error(object message); 

  void Fatal(object message); 

  //以上的每一个方法都有一个重载的方法,用来支持异常处理。 

 //每一个重载方法都如下所示,有一个异常类型的附加参数。 

  void Debug(object message, Exception ex); 

  // ... 

  //Boolean 属性用来检查Logger的日志级别 

  //(我们马上会在后面看到日志级别) 

  bool isDebugEnabled; 

  bool isInfoEnabled; 

  //… 其他方法对应的Boolean属性 

} 

    Log4net框架定义了一个叫做LogManager的类,用来管理所有的logger对象。它有一个GetLogger()静态方法,用我们提供的名字参数来检索已经存在的Logger对象。如果框架里不存在该Logger对象,它也会为我们创建一个Logger对象。代码如下所示:

log4net.ILog log = log4net.LogManager.GetLogger("logger-name"); 

通常来说,我们会以类(class)的类型(type)为参数来调用GetLogger(),以便跟踪我们正在进行日志记录的类。传递的类(class)的类型(type)可以用typeof(Classname)方法来获得,或者可以用如下的反射方法来获得:

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType 

  1.2 Repository

    Repository主要用于负责日志对象组织结构的维护。在log4net的以前版本中,框架仅支持分等级的组织结构(hierarchical organization)。这种等级结构本质上是库的一个实现,并且定义在log4net.Repository.Hierarchy 名字空间中。要实现一个Repository,需要实现log4net.Repository.ILoggerRepository 接口。但是通常并不是直接实现该接口,而是以log4net.Repository.LoggerRepositorySkeleton为基类继承。体系库 (hierarchical repository )则由log4net.Repository.Hierarchy.Hierarchy类实现。

如果你是个log4net框架的使用者,而非扩展者,那么你几乎不会在你的代码里用到Repository的类。相反的,你需要用到LogManager类来自动管理库和日志对象。

  1.3 Appender

    一个好的日志框架应该能够产生多目的地的输出。比如说输出到控制台或保存到一个日志文件。log4net 能够很好的满足这些要求。它使用一个叫做Appender的组件来定义输出介质。正如名字所示,这些组件把它们附加到Logger日志组件上并将输出传递到输出流中。你可以把多个Appender组件附加到一个日志对象上。 Log4net框架提供了几个Appender组件。关于log4net提供的Appender组件的完整列表可以在log4net框架的帮助手册中找到。有了这些现成的Appender组件,一般来说你没有必要再自己编写了。但是如果你愿意,可以从log4net.Appender.AppenderSkeleton类继承。 

  1.4 Appender Filters

    一个Appender 对象缺省地将所有的日志事件传递到输出流。Appender的过滤器(Appender Filters) 可以按照不同的标准过滤日志事件。在log4net.Filter的名字空间下已经有几个预定义的过滤器。使用这些过滤器,你可以按照日志级别范围过滤日志事件,或者按照某个特殊的字符串进行过滤。你可以在API的帮助文件中发现更多关于过滤器的信息。

  1.5 Layout

    一个Appender 对象缺省地将所有的日志事件传递到输出流。Appender的过滤器(Appender Filters) 可以按照不同的标准过滤日志事件。在log4net.Filter的名字空间下已经有几个预定义的过滤器。使用这些过滤器,你可以按照日志级别范围过滤日志事件,或者按照某个特殊的字符串进行过滤。你可以在API的帮助文件中发现更多关于过滤器的信息。

2.使用配置文件

  log4net框架会在相对于AppDomain.CurrentDomain.BaseDirectory 属性定义的目录路径下查找配置文件。框架在配置文件里要查找的唯一标识是<log4net>标签。一个完整的配置文件的例子如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler"></section>
    </configSections>
    <log4net>
    <appender name="errorAppender" type="log4net.Appender.RollingFileAppender">
        <filter type="log4net.Filter.LevelMatchFilter">
            <levelToMatch value="ERROR" />
        </filter>
        <filter type="log4net.Filter.DenyAllFilter" />
        <File value="Logs\err.log" />
        <PreserveLogFileNameExtension value="true" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value="yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <appender name="infoAppender" type="log4net.Appender.RollingFileAppender">
        <filter type="log4net.Filter.LevelMatchFilter">
            <levelToMatch value="INFO" />
        </filter>
        <filter type="log4net.Filter.DenyAllFilter" />
        <File value="Logs\info.log" />
        <PreserveLogFileNameExtension value="true" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value="yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <appender name="debugAppender" type="log4net.Appender.RollingFileAppender">
        <filter type="log4net.Filter.LevelMatchFilter">
            <levelToMatch value="DEBUG" />
        </filter>
        <filter type="log4net.Filter.DenyAllFilter" />
        <File value="Logs\debug.log" />
        <PreserveLogFileNameExtension value="true" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value="yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
        </layout>
    </appender>
    <appender name="perfAppender" type="log4net.Appender.RollingFileAppender">
        <filter type="log4net.Filter.LevelMatchFilter">
            <levelToMatch value="INFO" />
        </filter>
        <filter type="log4net.Filter.DenyAllFilter" />
        <File value="Logs\perf.log" />
        <PreserveLogFileNameExtension value="true" />
        <appendToFile value="true" />
        <rollingStyle value="Date" />
        <datePattern value="yyyyMMdd" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %logger - %message%newline" />
        </layout>
    </appender>
    <root>
        <level value="ALL" />
        <appender-ref ref="errorAppender" />
        <appender-ref ref="infoAppender" />
        <appender-ref ref="debugAppender" />
    </root>
    <logger name="Performance" additivity="false">
      <level value="ALL" />
      <appender-ref ref="perfAppender" />
    </logger>
</log4net>
</configuration> 


配置解析:

Appenders

<appender>标签的基本形式如上面所示。它定义了appender的名字和类型。 另外比较重要的是<appender>标签内部的其他标签。

The following appender type are defined in the log4net package:                   

                                    Type                                    Description
log4net.Appender.AdoNetAppender                                     Writes logging events to a database using either prepared statements or stored                                     procedures.                               
log4net.Appender.AnsiColorTerminalAppender                                     Writes color highlighted logging events to a an ANSI terminal window.                               
log4net.Appender.AspNetTraceAppender                                     Writes logging events to the ASP trace context. These can then be rendered at                                     the end of the ASP page or on the ASP trace page.                               
log4net.Appender.BufferingForwardingAppender                                     Buffers logging events before forwarding them to child appenders.                               
log4net.Appender.ColoredConsoleAppender                                     Writes logging events to the application's Console. The events may go to either                                     the standard our stream or the standard error stream. The events may have configurable                                    text and background colors defined for each level.                               
log4net.Appender.ConsoleAppender                                     Writes logging events to the application's Console. The events may go to either                                     the standard our stream or the standard error stream.                               
log4net.Appender.DebugAppender                                 Writes logging events to the .NET  system.                             
log4net.Appender.EventLogAppender                                     Writes logging events to the Windows Event Log.                               
log4net.Appender.FileAppender                                     Writes logging events to a file in the file system.                               
log4net.Appender.ForwardingAppender                                     Forwards logging events to child appenders.                               
log4net.Appender.LocalSyslogAppender                                     Writes logging events to the local syslog service (UNIX only).                               
log4net.Appender.MemoryAppender                                     Stores logging events in an in memory buffer.                               
log4net.Appender.NetSendAppender                                     Writes logging events to the Windows Messenger service. These messages are                                     displayed in a dialog on a users terminal.                               
log4net.Appender.OutputDebugStringAppender                                     Writes logging events to the debugger. If the application has no                                     debugger, the system debugger displays the string. If the application has no                                     debugger and the system debugger is not active, the message is ignored.                               
log4net.Appender.RemoteSyslogAppender                                     Writes logging events to a remote syslog service using UDP networking.                               
log4net.Appender.RemotingAppender                                     Writes logging events to a remoting sink using .NET remoting.                               
log4net.Appender.RollingFileAppender                                     Writes logging events to a file in the file system. The RollingFileAppender can                                     be configured to log to multiple files based upon date or file size                                     constraints.                               
log4net.Appender.SmtpAppender                                     Sends logging events to an email address.                               
log4net.Appender.SmtpPickupDirAppender                                     Writes SMTP messages as files into a pickup directory.                                    These files can then be read and sent by an SMTP agent                                    such as the IIS SMTP agent.                               
log4net.Appender.TelnetAppender                                     Clients connect via Telnet to receive logging events.                               
log4net.Appender.TraceAppender                                     Writes logging events to the .NET trace system.                               
log4net.Appender.UdpAppender                                     Sends logging events as connectionless UDP datagrams to a remote host or a                                     multicast group using a UdpClient.

有关每种appender的具体配置的例子,可以在log4net\doc\manual\example-config-appender.html中得到。

Appender元素里的<filter>标签

The following filter type are defined in the log4net package:                   

                                    Type                                    Description
log4net.Filter.DenyAllFilter                                     Drops all logging events.                               
log4net.Filter.LevelMatchFilter                                     An exact match to the event's level.                               
log4net.Filter.LevelRangeFilter                                     Matches against a range of levels.                               
log4net.Filter.LoggerMatchFilter                                     Matches against a the start of the logger name.                               
log4net.Filter.PropertyFilter                                     Matches a substring from a specific property value.                               
log4net.Filter.StringMatchFilter                                     Matches a substring from the event's message.                               

The filters can be configured to either accept or reject the event based upon the match.

Appender元素里的<Layouts>标签

The following layouts are included in the log4net package:                  

                                    Type                                    Description
log4net.Layout.ExceptionLayout                                     Renders the exception text from the logging                                     event.                              
log4net.Layout.PatternLayout                                     Formats the logging event according to a flexible                                     set of formatting flags.                              
log4net.Layout.RawTimeStampLayout                                     Extracts the timestamp from the logging event.                              
log4net.Layout.RawUtcTimeStampLayout                                     Extracts the timestamp from the logging event in Universal Time.                              
log4net.Layout.SimpleLayout                                     Formats the logging event very simply:                                    [level] - [message]
log4net.Layout.XmlLayout                                     Formats the logging event as an XML element.                              
log4net.Layout.XmlLayoutSchemaLog4j                                     Formats the logging event as an XML element that                                    complies with the log4j event dtd.

这里了解下:log4net.Layout.PatternLayout中的转换模式(ConversionPattern)

%m(message):输出的日志消息,如ILog.Debug(…)输出的一条消息

%n(new line):换行

%d(datetime):输出当前语句运行的时刻

%r(run time):输出程序从运行到执行到当前语句时消耗的毫秒数

%t(thread id):当前语句所在的线程ID

%p(priority): 日志的当前优先级别,即DEBUG、INFO、WARN…等

%c(class):当前日志对象的名称,例如:

       模式字符串为:%-10c -%m%n

       代码为:

ILog log=LogManager.GetLogger(“Exam.Log”);

log.Debug(“Hello”);

    则输出为下面的形式:

Exam.Log       - Hello

%L:输出语句所在的行号

%F:输出语句所在的文件名

%-数字:表示该项的最小长度,如果不够,则用空格填充

例如,转换模式为%r [%t]%-5p %c - %m%n 的 PatternLayout 将生成类似于以下内容的输出:

176 [main] INFO  org.foo.Bar - Located nearest gas station.


全文借鉴:http://www.cnblogs.com/dragon/archive/2005/03/24/124254.html

posted @ 2013-08-15 12:48  xiepeixing  阅读(2340)  评论(0编辑  收藏  举报