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

详细使用指南见文章: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.MdcFilter Matches a substring from a specific MDC value.
log4net.Filter.NdcFilter Matches a substring from the event's NDC.
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

Log4Net 手册的更多相关文章

  1. Apache log4net™ 手册——概述【翻译】

    原文地址 本文内容 概述 框架 日志(Loggers)和追加器(Appenders) 日志层次(Logger hierarchy) 追加器(Appenders) 筛选(Filters) 布局(Layo ...

  2. Apache log4net™ 手册——介绍【翻译】

    原文地址 本文内容 配置 配置属性 应用程序 appSettings 配置文件 配置语法 追加器(Appenders) 筛选器(Filters) 布局(Layouts) 根记录器(Root Logge ...

  3. Log4Net.Config配置信息《转》

    看了log4net的简单使用之一_log4net介绍 大家对log4net组件应该有了大概的了解,下面再近一步介绍其在项目中如何应用. 1.Logger 所有的记录器都必须实现 ILog 接口,该接口 ...

  4. log4net使用手册

    1. log4net简介 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.Java平台下,它还 ...

  5. [C#] 我的log4net使用手册

    1. log4net简介 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.Java平台下,它还 ...

  6. Log4net快速配置使用指南。(快速搭建log4net日志平台手册)

    每做一个新项目,都会用到log4net,但总是忘记如何快速配置.有时在网上搜半天也找不到好的模板,大都在介绍参数的使用,在此做下总结,争取下次用时仅10分钟就可搭建好log4net. 直接上介绍的步骤 ...

  7. Log4net - 规则简介

    参考页面: http://www.yuanjiaocheng.net/CSharp/csharprumenshili.html http://www.yuanjiaocheng.net/entity/ ...

  8. Log4net介绍

    一.Log4net介绍 log4net是一个功能著名的开源日志记录组件.利用log4net可以方便地将日志信息记录到文件.控制台.Windows事件日志和数据库(包括MS Server,Access, ...

  9. Log4net使用指南

    请在这里下载示例代码 1           简介 1.1          Log4net的优点: 几乎所有的大型应用都会有自己的用于跟踪调试的API.因为一旦程序被部署以后,就不太可能再利用专门的 ...

随机推荐

  1. paip.Java Annotation注解的作用and 使用

    paip.Java Annotation注解的作用and 使用 作者Attilax 艾龙,  EMAIL:1466519819@qq.com 来源:attilax的专栏 地址:http://blog. ...

  2. java 初学者需注意问题

    1.Java为什么能跨平台运行? Java语言编写的程序既是编译型的,又是解释型的.程序代码经过编译之后转换为一种Java字节码的中间语言,Java虚拟机即JVM将对字节码进行解释和运行.编译只进行一 ...

  3. Windows Error Code(windows错误代码详解)

    0 操作成功完成. 1 功能错误. 2 系统找不到指定的文件. 3 系统找不到指定的路径. 4 系统无法打开文件. 5 拒绝访问. 6 句柄无效. 7 存储控制块被损坏. 8 存储空间不足,无法处理此 ...

  4. Java插件开发-取插件下的某个文件

    //找到插件所在处 Bundle bundle = Activator.getDefault().getBundle(); //根据插件转义成URL路径 URL url = FileLocator.t ...

  5. C# 串口操作 ---- 系列文章

    C# 串口操作系列(5)--通讯库雏形 通讯库雏形的建立. 串口通讯介绍的高级篇,介绍更高级的抽象,为扩展为通用的客户端通讯库做铺垫,扩展性的考虑,能支持任意类型的流设备. ... 2010-08-0 ...

  6. 在线视频转gif动画工具 在线视频转gif动画工具下载

    在线视频转gif动画工具 在线视频转gif动画工具下载 http://www.leawo.cn/space-1723875-do-thread-id-60715.html http://www.lea ...

  7. Hadoop-2.6.0 + Zookeeper-3.4.6 + HBase-0.98.9-hadoop2环境搭建示例

    1    基本信息 1.1     软件信息 hadoop-2.6.0 zookeeper-3.4.6 hbase-0.98.9-hadoop2 (以下示例中使用的操作系统是Centos 6.5,请将 ...

  8. 设置Tomcat编码

    设置Tomcat编码 <Connector         port="8080"         maxThreads="150"         mi ...

  9. Crypto++入门学习笔记(DES、AES、RSA、SHA-256)(加解密)

    转自http://www.cppblog.com/ArthasLee/archive/2010/12/01/135186.html 最近,基于某些原因和需要,笔者需要去了解一下Crypto++库,然后 ...

  10. [转]java byte 数据类型(基础)

    package com.suypower.chengyu.test; public class ByteTest { /** * byte 8 bits -128 - + 127 * 1 bit = ...