log4net的使用大致可以总结为以下几步:
l 添加类库引用
把log4net的类库,加入程序引用即可。
l 指定配置名称
² 指定文件名的方式
[assembly: log4net.Config.XmlConfigurator(ConfigFile = ".log4net.config", Watch = true)]
² 指定扩展名的方式
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "log4net", Watch = true)]
log4net的配置文件到底是独立的,还是混合在web.config中,决定因素在于上面的ConfigFile这个参数传递的值。
// Summary:
// Gets or sets the filename of the configuration file.
//
// Remarks:
// If specified, this is the name of the configuration file to use with the
// log4net.Config.XmlConfigurator. This file path is relative to the application
// base directory (System.AppDomain.BaseDirectory).
// The log4net.Config.XmlConfiguratorAttribute.ConfigFile takes priority over
// the log4net.Config.XmlConfiguratorAttribute.ConfigFileExtension.
public string ConfigFile { get; set; }
//
// Summary:
// Gets or sets the extension of the configuration file.
//
// Remarks:
// If specified this is the extension for the configuration file. The path
// to the config file is built by using the application base directory (System.AppDomain.BaseDirectory),
// the assembly file name and the config file extension.
// If the log4net.Config.XmlConfiguratorAttribute.ConfigFileExtension is set
// to MyExt then possible config file names would be: MyConsoleApp.exe.MyExt
// or MyClassLibrary.dll.MyExt.
// The log4net.Config.XmlConfiguratorAttribute.ConfigFile takes priority over
// the log4net.Config.XmlConfiguratorAttribute.ConfigFileExtension.
public string ConfigFileExtension { get; set; }
注意:这个配置文件,应该存在System.AppDomain.BaseDirectory目录(一般和web.config同级即是)。
到底是以文件名为准,还是以扩展名为准。看了log4net中属性的注释,我想你心里已经很清楚了。
无论哪种方式,都需要在程序代码里,指定配置文件的名称或扩展名。另外, 以上无论那种方式,都需要把这行代码放在项目的代码中,一般建议存放在Properties\AssemblyInfo.cs中即可,当然也可以放在别的代码中。
我尝试了放在Global.asax.cs中,发现也可以工作。
注意:
这个“Watch = true”,参数是指配置文件内容更改后,log4net是否重新载入新的配置数据。
按照log4net的类库注释:
//
// Summary:
// Gets or sets a value indicating whether to watch the configuration file.
//
// Remarks:
// If this flag is specified and set to true then the framework will watch
// the configuration file and will reload the config each time the file is modified.
// The config file can only be watched if it is loaded from local disk. In
// a No-Touch (Smart Client) deployment where the application is downloaded
// from a web server the config file may not reside on the local disk and therefore
// it may not be able to watch it.
// Watching configuration is not supported on the SSCLI.
public bool Watch { get; set; }
从上面的注释,我们可以解读到:Watch这个开关,可以监视配置文件的改动。因此,我们不适合把log4net的配置混合到web.config中。原来很简单,web.config里改动了数据库的连接字符串,也会导致这个配置数据会重新载入一回。
l 在配置文件里增加的内容
² 对配置的引用
无论是在web.config中,还是另外的配置文件中,都要存在以下内容:
1. 根必须是:<configuration>
2. <configuration> 下的<configSections>中,增加以下内容
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
3. 下面是log4net中的具体的具体配置项的内容。
从我的实验结果得到,如果指定文件的扩展名,上面的1和2的内容可以是免去的。即在独立的配置文件中,xml的根节点,可以直接是<log4net>,这样也可以工作。至于原理还没彻底搞明白。
² 各种Appender的简单介绍
log4net有多种内置Appender
在log4net的配置中,appender是最重要的部分,一般来说,每一种appender都表示一种日志的输出介质,如日志文件、EvengLog、数据库、控制台、邮件、Trace、ASP.NET页面等。
本文对各种内置的appender的配置提供了示例,但却远称不上详尽。要想了解每一种appender的参数和选项的说明,请参看该appender的SDK文档。
u Appender可以自己定制的。
这个从官网,查找SDK及SDK使用说明即可。
u Appender,默认是非排他的。
即log可以往多个Appender中同时发送。比如既可以往Console(控制台)输出,又可以往文本文件里写,还可以同时往数据库(Oracle,SQLServer,Access等)标准数据库里写。
日志能不能往XML格式的文本文件里写?应该是可以的,怎么配置?
下面是我试验的既往Console(控制台),又往文本文件里输出日志的功能截图。
关于各种Appender的详细介绍,我也不准备在这里大花笔墨(不是一时半会能写全面的),
摘录官网公布的内置Appender类:
Class | Description |
Appender that logs to a database. | |
Parameter type used by the AdoNetAppender. | |
Appends logging events to the terminal using ANSI color escape sequences. | |
AnsiColorTerminalAppender.LevelColors | A class to act as a mapping between the level that a logging call is made at and the color it should be displayed as. |
A strongly-typed collection of IAppender objects. | |
Abstract base class implementation of IAppender. | |
Appends log events to the ASP.NET TraceContext system. | |
Abstract base class implementation of IAppender that buffers events in a fixed size buffer. | |
BufferingForwardingAppender | Buffers events and then forwards them to attached appenders. |
Appends logging events to the console. | |
ColoredConsoleAppender.LevelColors | A class to act as a mapping between the level that a logging call is made at and the color it should be displayed as. |
Appends logging events to the console. | |
Appends log events to the Debug system. | |
Writes events to the system event log. | |
EventLogAppender.Level2EventLogEntryType | A class to act as a mapping between the level that a logging call is made at and the color it should be displayed as. |
Appends logging events to a file. | |
FileAppender.ExclusiveLock | Hold an exclusive lock on the output file |
FileAppender.InterProcessLock | Provides cross-process file locking. |
FileAppender.LockingModelBase | Locking model base class |
Acquires the file lock for each write | |
This appender forwards logging events to attached appenders. | |
Logs events to a local syslog service. | |
LocalSyslogAppender.LevelSeverity | A class to act as a mapping between the level that a logging call is made at and the syslog severity that is should be logged at. |
Stores logging events in an array. | |
Logs entries by sending network messages using the NetMessageBufferSend native function. | |
Appends log events to the OutputDebugString system. | |
Logs events to a remote syslog daemon. | |
RemoteSyslogAppender.LevelSeverity | A class to act as a mapping between the level that a logging call is made at and the syslog severity that is should be logged at. |
Delivers logging events to a remote logging sink. | |
Appender that rolls log files based on size or date or both. | |
Send an e-mail when a specific logging event occurs, typically on errors or fatal errors. | |
Send an email when a specific logging event occurs, typically on errors or fatal errors. Rather than sending via smtp it writes a file into the directory specified by PickupDir. This allows services such as the IIS SMTP agent to manage sending the messages. | |
Appender that allows clients to connect via Telnet to receive log messages | |
TelnetAppender.SocketHandler | Helper class to manage connected clients |
TelnetAppender.SocketHandler.SocketClient | Class that represents a client connected to this handler |
Sends logging events to a TextWriter. | |
Appends log events to the Trace system. | |
Sends logging events as connectionless UDP datagrams to a remote host or a multicast group using an UdpClient. |
² Root中指定哪些Appender起作用
² <root>
² <level value="WARN" />
² <appender-ref ref="LogFileAppender" />
² <appender-ref ref="ConsoleAppender" />
² <appender-ref ref="NetSendAppender" />
² </root>
“ref”指定的值,是上面给各种Appender定义的名称,注意不是Appender的类名
² 在配置文件中声明一些logger分类的等级
² <!-- Specify the level for some specific categories -->
² <logger name="ProjectManagement">
² <level value="ALL" />
² <appender-ref ref="LogFileAppender" />
² </logger>
l log4net的代码调用
代码调用大致如此:
添加引用using log4net;
l private static readonly ILog logger = LogManager.GetLogger("ProjectManagement");
l 记录任何信息,包括异常
l logger.Error(Server.GetLastError());
具体LogManager.GetLogger这个方法的使用介绍:
如下内容,是从类库的注释里摘录的一个。GetLogger这个方法,有多个重载参数形式,具体查看类库注释。
//
// Summary:
// Retrieves or creates a named logger.
//
// Parameters:
// name:
// The name of the logger to retrieve.
//
// Returns:
// The logger with the name specified.
//
// Remarks:
// Retrieves a logger named as the name parameter. If the named logger already
// exists, then the existing instance will be returned. Otherwise, a new instance
// is created.
// By default, loggers do not have a set level but inherit it from the hierarchy.
// This is one of the central features of log4net.
public static ILog GetLogger(string name);
附件
本文件下,两个.cs代码:
log4net.Config.XmlConfiguratorAttribute.cs
log4net.LogManager.cs
这两个文件,都是log4net类库中相关类的方法的原型的定义,含注释。