log4net的配置和使用

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里改动了数据库的连接字符串,也会导致这个配置数据会重新载入一回。

以上内容,有两篇参考文档(部分内容写的可能不准确),仅供参考不可作为“金条玉律”:

http://www.codeproject.com/KB/dotnet/ConfigureLog4Net.aspx

http://blog.csdn.net/aspnet2002web/article/details/6046655

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(控制台),又往文本文件里输出日志的功能截图。

clip_image002

关于各种Appender的详细介绍,我也不准备在这里大花笔墨(不是一时半会能写全面的),我这里找了几篇比较精练的文章:

两篇来自官网:

http://logging.apache.org/log4net/release/config-examples.html

http://logging.apache.org/log4net/release/sdk/log4net.Appender.html

另一篇来自技术博客:

http://www.beefycode.com/post/Log4Net-Tutorial-pt-3-Appenders.aspx

摘录官网公布的内置Appender类:

Class

Description

AdoNetAppender

Appender that logs to a database.

AdoNetAppenderParameter

Parameter type used by the AdoNetAppender.

AnsiColorTerminalAppender

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.

AppenderCollection

A strongly-typed collection of IAppender objects.

AppenderSkeleton

Abstract base class implementation of IAppender.

AspNetTraceAppender

Appends log events to the ASP.NET TraceContext system.

BufferingAppenderSkeleton

Abstract base class implementation of IAppender that buffers events in a fixed size buffer.

BufferingForwardingAppender

Buffers events and then forwards them to attached appenders.

ColoredConsoleAppender

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.

ConsoleAppender

Appends logging events to the console.

DebugAppender

Appends log events to the Debug system.

EventLogAppender

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.

FileAppender

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

FileAppender.MinimalLock

Acquires the file lock for each write

ForwardingAppender

This appender forwards logging events to attached appenders.

LocalSyslogAppender

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.

MemoryAppender

Stores logging events in an array.

NetSendAppender

Logs entries by sending network messages using the NetMessageBufferSend native function.

OutputDebugStringAppender

Appends log events to the OutputDebugString system.

RemoteSyslogAppender

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.

RemotingAppender

Delivers logging events to a remote logging sink.

RollingFileAppender

Appender that rolls log files based on size or date or both.

SmtpAppender

Send an e-mail when a specific logging event occurs, typically on errors or fatal errors.

SmtpPickupDirAppender

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.

TelnetAppender

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

TextWriterAppender

Sends logging events to a TextWriter.

TraceAppender

Appends log events to the Trace system.

UdpAppender

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类库中相关类的方法的原型的定义,含注释。

你可能感兴趣的:(log)