log4net是一个可以帮助程序员把日志信息输出到各种不同目标的.net类库。它可以容易的加载到开发项目中,实现程序调试和运行的时候的日志信息输出,提供了比.net自己提供的debug类和trace类的功能更多。log4net是从java下有卓越表现的log4j移植过来的。它是 apache基金资助的项目的一部分。
========================================================
log4net Features
Overview
log4net is a tool to help the programmer output log statements to avariety of output targets. In case of problems with an application, it ishelpful to enable logging so that the problem can be located. With log4net itis possible to enable logging at runtime without modifying the applicationbinary. The log4net package is designed so that log statements can remain inshipped code without incurring a high performance cost. It follows that thespeed of logging (or rather not logging) is crucial.
At the same time, log output can be so voluminous that it quickly becomesoverwhelming. One of the distinctive features of log4net is the notion ofhierarchical loggers. Using these loggers it is possible to selectively controlwhich log statements are output at arbitrary granularity.
log4net is designed with two distinct goals in mind: speed and flexibility
Features
- Support for multiple frameworks
- Output to multiple logging targets
- Hierarchical logging architecture
- XML Configuration
- Dynamic Configuration
- Logging Context
- Proven architecture
- Modular and extensible design
- High performance with flexibility
Support for multiple frameworks
log4net runs on all ECMA CLI 1.0 compatible runtimes. log4nethas specific builds for the following frameworks:
- Microsoft .NET Framework 1.0 (1.0.3705)
- Microsoft .NET Framework 1.1 (1.1.4322)
- Microsoft .NET Framework 2.0 (2.0.50727)
- Microsoft .NET Compact Framework 1.0
- Mono 1.0
- Mono 2.0
- Microsoft Shared Source CLI 1.0
- CLI 1.0 Compatible
Note: Due to the .NET frameworks support for backwardcompatibility log4net will run on future versions of the runtimes listed above.
Output to multiple logging targets
log4net ships with the following appenders (not on all frameworks):
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.ColoredConsoleAppender |
Writes color highlighted logging events to the application's Windows Console. |
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.EventLogAppender |
Writes logging events to the Windows Event Log. |
log4net.Appender.FileAppender |
Writes logging events to a file in the file system. |
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.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. |
Hierarchical logging architecture
Hierarchical logging is an ideal fit with component baseddevelopment. Each component has its own of logger. When individually tested,the properties of these loggers may be set as the developer requires. Whencombined with other components, the loggers inherit the properties determinedby the integrator of the components. One can selectively elevate loggingpriorities on one component without affecting the other components. This isuseful when you need a detailed trace from just a single component without crowdingthe trace file with messages from other components. All this can be donethrough configuration files; no code changes are required.
XML Configuration
log4net is configured using an XML configuration file.The configuration information can be embedded within other XML configurationfiles (such as the application's .config file) or in a separate file. Theconfiguration is easily readable and updateable while retaining the flexibilityto express all configurations. Alternatively log4net can be configuredprogrammatically.
DynamicConfiguration
log4net can monitor its configuration file for changesand dynamically apply changes made by the configurator. The logging levels,appenders, layouts, and just about everything else can be adjusted at runtime. Inmany cases it is possible to diagnose application issues without terminatingthe process in question. This can a very valuable tool in investigating issueswith deployed applications.
Logging Context
log4net can be used to collect logging context data in away that is transparent to the developer at the point of logging. TheGlobalContext and the ThreadContext allow the application to store contextualdata that is attached to logging messages. For instance, in a web service, oncethe caller is authenticated the username of the caller could be stored in aThreadContext property. This property would then be automatically logged aspart of each subsequent logging message made from the same thread.
Provenarchitecture
log4net is based on the highly successful log4j logginglibrary, in development since 1996. This popular and proven architecture has sofar been ported to 12 languages.
========================================================
log4net Examples
Overview
The following examples are only available in the log4net release download,not on-line. To obtain the examples download one of thelog4net releases.
Building Examples
Building AnExample
A single example can be build by running nant from the example directory.
For example running nant in the examples\net\1.0\Tutorials\ConsoleApp\csdirectory will build the C# version of the .NET 1.0 ConsoleApp example.
nant can be run in any directory containing a nant.build file. The typicalbehavior of the build file is to build all projects under the currentdirectory.
For example running nant in the examples\net\1.1 directory will build allthe examples for the .NET 1.1 platform.
Building AllExamples
To build all the examples either run nant in the examples directory or youcan specify the compile-examples target to the main log4net nant build.
Visual Studio .NET
There are Visual Studio .NET 2002 project files for the .NET 1.0framework. The solution files for C# and VB are in the examples\net\1.0 folder.
For the Managed C++ project there is a Visual Studio .NET 2003 projectfile in the examples\net\1.1folder.
Examples
Tutorial -ConsoleApp
ConsoleApp shows how to write a simple console application thatinitializes logging and logs various events.
This example is available for the following platforms and languages. If aversion is not available for your chosen platform and language combination thenselect the nearest platform for the appropriate language.
To run this example execute ConsoleApp.exe from the buildoutput directory.
Tutorial - WebApp
ConsoleApp shows how to write a simple ASP.NET webapplication that initializes logging and logs various events. This example isavailable for the following platforms and languages. If a version is notavailable for your chosen platform and language combination then select thenearest platform for the appropriate language.
To run this example you need to have an ASP.NET containerapplication to host the web application, for example IIS. In IIS create a newvirtual directory pointing to the WebApp src directory. Configure IIS torecognize this virtual directory as an application. Open up a web browser,navigate to the virtual directory and to the WebForm1.aspx page within it.
Remoting -RemotingClient
The RemotingClient application is a simple consoleapplication that configures log4net with the RemotingAppender. This appenderwill attempt to deliver the logging events to a remoting listener. This exampleshould be run in conjunction with the RemotingServer. This example is availablefor the following platforms and languages. If a version is not available foryour chosen platform and language combination then select the nearest platformfor the appropriate language.
To run this example execute RemotingClient.exe from thebuild output directory.
Remoting -RemotingServer
The RemotingServer application is a simple console application thatlistens for logging events from a remote RemotingAppender and then logs themthrough the local log4net instance. This example should be run in conjunctionwith the RemotingClient.
This example is available for the following platforms and languages. If aversion is not available for your chosen platform and language combination thenselect the nearest platform for the appropriate language.
To run this example execute RemotingServer.exe from thebuild output directory. While this process is running execute the RemotingClient.exeprogram on the same machine. The logging events from the client are transferredto the server.
Repository -SimpleModule
The SimpleModule is a class library that is intended to be used as part ofthe SimpleApp example, This class library uses the log4net.Config.Repositoryattribute to create a separate configuration space from other assemblies.
This example is available for the following platforms and languages. If aversion is not available for your chosen platform and language combination thenselect the nearest platform for the appropriate language.
This library is intended to be used as part of the SimpleAppexample.
Repository -SharedModule
The SharedModule is a class library that is intended tobe used as part of the SimpleApp example, This class library uses log4net butdoes not attempt to configure logging. This example is available for the followingplatforms and languages. If a version is not available for your chosen platformand language combination then select the nearest platform for the appropriatelanguage.
This library is intended to be used as part of theSimpleApp example.
Repository -SimpleApp
The SimpleApp example uses the SimpleModule andSharedModule to demonstrate the ways in which multiple assemblies within thesame process may be separately configured. This example is available for thefollowing platforms and languages. If a version is not available for yourchosen platform and language combination then select the nearest platform forthe appropriate language.
To run this example execute SimpleApp.exe from the buildoutput directory.
Extensibility- EventIDLogApp
The EventIDLogApp example demonstrates using thelog4net.Ext.EventID extension. The extension needs to be built separately fromthe extensions\net\1.0\log4net.Ext.EventID directory. This example is availablefor the following platforms and languages. If a version is not available foryour chosen platform and language combination then select the nearest platformfor the appropriate language.
To run this example execute EventIDLogApp.exe from thebuild output directory.
Extensibility- TraceLogApp
The TraceLogApp example demonstrates using thelog4net.Ext.Trace extension. The extension needs to be built separately fromthe extensions\net\1.0\log4net.Ext.Trace directory. This example is availablefor the following platforms and languages. If a version is not available foryour chosen platform and language combination then select the nearest platformfor the appropriate language.
To run this example execute TraceLogApp.exe from thebuild output directory.
SampleAppenders
This project includes the following example appenders.
- AsyncAppender
- FastDbAppender
- FireEventAppender
- MessageBoxAppender
- MessageObjectExpanderAppender
- MsmqAppender
- PatternFileAppender
- SimpleSmtpAppender
This example is available for the following platforms andlanguages. If a version is not available for your chosen platform and languagecombination then select the nearest platform for the appropriate language.
To run this example execute SampleAppendersApp.exe fromthe build output directory.
SampleLayouts
This project includes the following example layouts.
- ForwardingLayout
- LineWrappingLayout
This example is available for the following platforms andlanguages. If a version is not available for your chosen platform and languagecombination then select the nearest platform for the appropriate language.
To run this example execute SampleLayoutsApp.exe from thebuild output directory.
Performance -NotLogging
The NotLogging example benchmarks the performance oflog4net logging statements in user code in various scenarios including whenlogging is disabled. This example is available for the following platforms andlanguages. If a version is not available for your chosen platform and languagecombination then select the nearest platform for the appropriate language.
WmiAppender
The WmiAppender sample shows an example appender thatfires events through Windows Management Instrumentation. This example isavailable for the following platforms and languages. If a version is notavailable for your chosen platform and language combination then select the nearestplatform for the appropriate language.
========================================================
log4net Config ExamplesOverviewThis document presents example configurations for thebuilt-in appenders. These configurations are designed to work with the log4net.Config.DOMConfigurator and the log4net.Repository.Hierarchy.Hierarchy.
These examples are by no means exhaustive configurationsfor the appenders. For a full list of the parameters that can be specified toeach appender and more details on each options see the SDK documentation forthe appender.
AdoNetAppenderFor full details see the SDK Reference entry:
log4net.Appender.AdoNetAppender.
The configuration of the AdoNetAppenderdepends on the provider selected for the target database. Here are someexamples.
MS SQL ServerThe following example shows how to configure the AdoNetAppender to log messages to a SQL Server database. Theevents are written in batches of 100 (
BufferSize). The
ConnectionTypespecifies the fully qualified type name for the System.Data.IDbConnectionto use to connect to the database. The
ConnectionString is databaseprovider specific. The
CommandText is either a prepared statement or astored procedure, in this case it is a prepared statement. Each parameter tothe prepared statement or stored procedure is specified with its name, databasetype and a layout that renders the value for the parameter.
The database table definition is:
CREATE TABLE [dbo].[Log] (
[Id] [int] IDENTITY (1, 1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar] (255) NOT NULL,
[Level] [varchar] (50) NOT NULL,
[Logger] [varchar] (255) NOT NULL,
[Message] [varchar] (4000) NOT NULL,
[Exception] [varchar] (2000) NULL)
The appender configuration is:
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=[database server];initial catalog=[database name];integrated security=false;persist security info=True;User ID=[user];Password=[password]" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter></appender>
MS AccessThis example shows how to write events to an AccessDatabase.
<appender name="AdoNetAppender_Access" type="log4net.Appender.AdoNetAppender">
<connectionString value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\log\access.mdb;User Id=;Password=;" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date" />
</layout>
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="1024" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter></appender>
Oracle9iThis example shows how to write events to an Oracle9iDatabase.
The database table definition is:
create table log (
Datetime timestamp(3),
Thread varchar2(255),
Log_Level varchar2(255),
Logger varchar2(255),
Message varchar2(4000)
);
The appender configuration is:
<appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender">
<connectionType value="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=[mydatabase];User ID=[user];Password=[password]" />
<commandText value="INSERT INTO Log (Datetime,Thread,Log_Level,Logger,Message) VALUES (:log_date, :thread, :log_level, :logger, :message)" />
<bufferSize value="128" />
<parameter>
<parameterName value=":log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value=":thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value=":log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value=":logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value=":message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter></appender>
Oracle8iThis example shows how to write events to an Oracle8iDatabase.
The database table definition is:
CREATE TABLE CSAX30.LOG(
THREAD
VARCHAR2(255),
LOG_LEVEL
VARCHAR2(255),
LOGGER
VARCHAR2(255),
MESSAGE
VARCHAR2(4000))TABLESPACE CSAX30D LOGGING
The appender configuration is:
<appender name="AdoNetAppender_Oracle" type="log4net.Appender.AdoNetAppender">
<connectionType value ="System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=<dsname>;User ID=<userid>;Password=<password>" />
<commandText value="INSERT INTO Log (Log_Level,Logger,Message) VALUES (:log_level, :logger, :message)" />
<bufferSize value="250" />
<parameter>
<parameterName value=":log_level" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value=":logger" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value=":message" />
<dbType value="String" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter></appender>
IBM DB2This example shows how to write events to an IBM DB2 8.2Database. The following syntax should also work with older DB2 databaseservers.
The database table definition is:
CREATE TABLE "myschema.LOG" (
"ID" INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (
START WITH +1
INCREMENT BY +1
MINVALUE +1
MAXVALUE +2147483647
NO CYCLE
NO CACHE
NO ORDER
),
"DATE" TIMESTAMP NOT NULL,
"THREAD" VARCHAR(255) NOT NULL,
"LEVEL" VARCHAR(500) NOT NULL,
"LOGGER" VARCHAR(255) NOT NULL,
"MESSAGE" VARCHAR(4000) NOT NULL,
"EXCEPTION" VARCHAR(2000))IN "LRGTABLES";
The appender configuration is:
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="IBM.Data.DB2.DB2Connection,IBM.Data.DB2, Version=8.1.2.1" />
<connectionString value="server=192.168.0.0;database=dbuser;user Id=username;password=password;persist security info=true" />
<commandText value="INSERT INTO myschema.Log (Date,Thread,Level,Logger,Message,Exception) VALUES (@log_date,@thread,@log_level,@logger,@message,@exception)" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="500" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="@exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter></appender>
SQLiteThis example shows how to write events to a SQLiteDatabase. This was tested against v0.21 of the
SQLite .NET provider.
SQLite doesn't have strongly-typed columns or field lengthsbut its recommended you still include this information for readability. Thedatabase table definition is:
CREATE TABLE Log (
LogId
INTEGER PRIMARY KEY,
Date
DATETIME NOT NULL,
Level
VARCHAR(50) NOT NULL,
Logger
VARCHAR(255) NOT NULL,
Message
TEXT DEFAULT NULL);
The appender configuration is:
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="Finisar.SQLite.SQLiteConnection, SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c" />
<connectionString value="Data Source=c:\\inetpub\\wwwroot\\logs\\log4net.db;Version=3;" />
<commandText value="INSERT INTO Log (Date, Level, Logger, Message) VALUES (@Date, @Level, @Logger, @Message)" />
<parameter>
<parameterName value="@Date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@Level" />
<dbType value="String" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@Logger" />
<dbType value="String" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@Message" />
<dbType value="String" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter></appender>
AspNetTraceAppenderFor full details see the SDK Reference entry:
log4net.Appender.AspNetTraceAppender.
The following example shows how to configure the AspNetTraceAppender to log messages to the ASP.NETTraceContext. The messages are written to the System.Web.TraceContext.Writemethod if they are below level WARN. If they are WARN or above they are written to the System.Web.TraceContext.Warnmethod.
<appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
BufferingForwardingAppenderFor full details see the SDK Reference entry:
log4net.Appender.BufferingForwardingAppender.
The following example shows how to configure the BufferingForwardingAppender to buffer 100 messages beforedelivering them to the
ConsoleAppender.
<appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
<bufferSize value="100"/>
<appender-ref ref="ConsoleAppender" /></appender>
This example shows how to deliver only significant events.A LevelEvaluator is specified with a threshold of WARN. This means that the events will only be delivered whena message with level of WARN or higher level is logged.Up to 512 (
BufferSize) previous messages of any level will also bedelivered to provide context information. Messages not sent will be discarded.
<appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<appender-ref ref="ConsoleAppender" /></appender>
ColoredConsoleAppenderFor full details see the SDK Reference entry:
log4net.Appender.ColoredConsoleAppender.
The following example shows how to configure the ColoredConsoleAppender to log messages to the console. Bydefault the messages are sent to the console standard output stream. Thisexample shows how to highlight error messages.
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example shows how to colorize multiple levels.
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<backColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
ConsoleAppenderFor full details see the SDK Reference entry:
log4net.Appender.ConsoleAppender.
The following example shows how to configure the ConsoleAppender to log messages to the console. By defaultthe messages are sent to the console standard output stream.
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example shows how to direct the log messages to theconsole error stream.
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<target value="Console.Error" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
EventLogAppenderFor full details see the SDK Reference entry:
log4net.Appender.EventLogAppender.
The following example shows how to configure the EventLogAppender to log to the
Application event logon the local machine using the event
Source of the AppDomain.FriendlyName.
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example shows how to configure the EventLogAppenderto use a specific event
Source.
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="MyApp" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
For more information on how to setup the event log to allowthe EventLogAppender to write to it, see the FAQ:
Whydoesn't the EventLogAppender work?.
FileAppenderFor full details see the SDK Reference entry:
log4net.Appender.FileAppender.
The following example shows how to configure the FileAppender to write messages to a file. The file specifiedis
log-file.txt. The file will be appended to rather than overwritteneach time the logging process starts.
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example shows how to configure the file name to writeto using an environment variable
TMP. The encoding to use to write tothe file is also specified.
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="${TMP}\log-file.txt" />
<appendToFile value="true" />
<encoding value="unicodeFFFE" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example shows how to configure the appender to use theminimal locking model that allows multiple processes to write to the same file.
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="${TMP}\log-file.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
ForwardingAppenderFor full details see the SDK Reference entry:
log4net.Appender.ForwardingAppender.
The following example shows how to configure the ForwardingAppender. The forwarding appender allows a set ofconstraints to be used to decorate an appender. In this example the
ConsoleAppenderis decorated with a
Threshold of level WARN.This means that an event directed to the
ConsoleAppender directly willbe logged regardless of its level, but an event directed to the
ForwardingAppenderwill only be passed on to the
ConsoleAppender if its level is WARN or higher. This appender is used only in specialcircumstances.
<appender name="ForwardingAppender" type="log4net.Appender.ForwardingAppender" >
<threshold value="WARN"/>
<appender-ref ref="ConsoleAppender" /></appender>
MemoryAppenderFor full details see the SDK Reference entry:
log4net.Appender.MemoryAppender.
It is unlikely that the MemoryAppenderwill be configured using a config file, but if you want to do it here's how.
<appender name="MemoryAppender" type="log4net.Appender.MemoryAppender">
<onlyFixPartialEventData value="true" /></appender>
NetSendAppenderFor full details see the SDK Reference entry:
log4net.Appender.NetSendAppender.
The following example shows how to configure the NetSendAppender to deliver messages to a specific user'sscreen. As this appender is typically only used for important notifications a
Thresholdof level Error is specified. This example delivers themessages to the user
nicko on the machine
SQUARE. However thingsare not always straight forward using the Windows Messenger Service, onepossible outcome using this configuration is that the
Server willbroadcast looking for a WINS server which it will then ask to deliver themessage to the
Recipient, the WINS server will deliver it to the firstterminal that the user logged in from.
<appender name="NetSendAppender" type="log4net.Appender.NetSendAppender">
<threshold value="ERROR" />
<server value="SQUARE" />
<recipient value="nicko" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
OutputDebugStringAppenderFor full details see the SDK Reference entry:
log4net.Appender.OutputDebugStringAppender.
The following example shows how to configure the OutputDebugStringAppender to write logging messages to the OutputDebugString API.
<appender name="OutputDebugStringAppender" type="log4net.Appender.OutputDebugStringAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
RemotingAppenderFor full details see the SDK Reference entry:
log4net.Appender.RemotingAppender.
The following example shows how to configure the RemotingAppender to deliver logging events to a specified
Sink(in this example the sink is tcp://localhost:8085/LoggingSink).In this example the events are delivered in blocks of 95 events because of the
BufferSize.No events are discarded. The
OnlyFixPartialEventData option allows theappender to ignore certain logging event properties that can be very slow togenerate (e.g. the calling location information).
<appender name="RemotingAppender" type="log4net.Appender.RemotingAppender" >
<sink value="tcp://localhost:8085/LoggingSink" />
<lossy value="false" />
<bufferSize value="95" />
<onlyFixPartialEventData value="true" /></appender>
This example configures the RemotingAppenderto deliver the events only when an event with level ERRORor above is logged. When the events are delivered, up to 200 (
BufferSize)previous events (regardless of level) will be delivered to provide context.Events not delivered will be discarded.
<appender name="RemotingAppender" type="log4net.Appender.RemotingAppender" >
<sink value="tcp://localhost:8085/LoggingSink" />
<lossy value="true" />
<bufferSize value="200" />
<onlyFixPartialEventData value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR"/>
</evaluator></appender>
RollingFileAppenderFor full details see the SDK Reference entry:
log4net.Appender.RollingFileAppender.
The RollingFileAppender builds onthe FileAppender and has the same options as thatappender.
The following example shows how to configure the RollingFileAppender to write to the file
log.txt. Thefile written to will always be called
log.txt because the
StaticLogFileNameparam is specified. The file will be rolled based on a size constraint (
RollingStyle).Up to 10 (
MaxSizeRollBackups) old files of 100 KB each (
MaximumFileSize)will be kept. These rolled files will be named:
log.txt.1,
log.txt.2,
log.txt.3, etc...
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example show how to configure the RollingFileAppenderto roll log files on a date period. This example will roll the log file everyminute! To change the rolling period adjust the DatePatternvalue. For example, a date pattern of "yyyyMMdd"will roll every day. See System.Globalization.DateTimeFormatInfofor a list of available patterns.
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logfile" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd-HHmm" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example show how to configure the RollingFileAppenderto roll log files on a date period and within a date period on file size. Foreach day only the last 10 files of 1MB will be kept.
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logfile" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
This example show how to configure the RollingFileAppenderto roll log files once per program execution. The appendToFileproperty is set to false to prevent the appender fromoverwriting the existing files. The maxSizeRollBackupsis set to negative 1 to allow an infinite number of backup files. The file sizedoes have to be limited but here it is set to 50 Gigabytes which, if a log fileexceeds this size limit during a single run then it will also be rolled.
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logfile.txt" />
<appendToFile value="false" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="-1" />
<maximumFileSize value="50GB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
SmtpAppenderFor full details see the SDK Reference entry:
log4net.Appender.SmtpAppender.
The following example shows how to configure the SmtpAppender to deliver log events via SMTP email. The
To,
From,
Subject and
SmtpHost are required parameters. Thisexample shows how to deliver only significant events. A LevelEvaluatoris specified with a threshold of WARN. This means thatan email will be sent for each WARN or higher levelmessage that is logged. Each email will also contain up to 512 (
BufferSize)previous messages of any level to provide context. Messages not sent will bediscarded.
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="to@domain.com" />
<from value="from@domain.com" />
<subject value="test logging message" />
<smtpHost value="SMTPServer.domain.com" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
</layout></appender>
This example shows how to configure the SmtpAppenderto deliver all messages in emails with 512 (
BufferSize) messages peremail.
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="to@domain.com" />
<from value="from@domain.com" />
<subject value="test logging message" />
<smtpHost value="SMTPServer.domain.com" />
<bufferSize value="512" />
<lossy value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
</layout></appender>
This example shows a more verbose formatting layout for themail messages.
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender,log4net">
<to value="to@domain.com" />
<from value="from@domain.com" />
<subject value="test logging message" />
<smtpHost value="SMTPServer.domain.com" />
<bufferSize value="512" />
<lossy value="false" />
<evaluator type="log4net.Core.LevelEvaluator,log4net">
<threshold value="WARN" />
</evaluator>
<layout type="log4net.Layout.PatternLayout,log4net">
<conversionPattern value="%property{log4net:HostName} :: %level :: %message %newlineLogger: %logger%newlineThread: %thread%newlineDate: %date%newlineNDC: %property{NDC}%newline%newline" />
</layout></appender>
SmtpPickupDirAppenderFor full details see the SDK Reference entry:
log4net.Appender.SmtpPickupDirAppender.
The SmtpPickupDirAppender isconfigured similarly to the SmtpAppender. The onlydifference is that rather than specify a
SmtpHost parameter a
PickupDirmust be specified.
The
PickupDir parameter is a path that must existand the code executing the appender must have permission to create new filesand write to them in this directory. The path is relative to the application'sbase directory (AppDomain.BaseDirectory).
The following example shows how to configure the SmtpPickupDirAppender to deliver log events via SMTP email.The
To,
From,
Subject and
PickupDir are requiredparameters. This example shows how to deliver only significant events. A LevelEvaluator is specified with a threshold of WARN. This means that an email will be sent for each WARN or higher level message that is logged. Each email willalso contain up to 512 (
BufferSize) previous messages of any level toprovide context. Messages not sent will be discarded.
<appender name="SmtpPickupDirAppender" type="log4net.Appender.SmtpPickupDirAppender">
<to value="to@domain.com" />
<from value="from@domain.com" />
<subject value="test logging message" />
<pickupDir value="C:\SmtpPickup" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
</layout></appender>
TraceAppenderFor full details see the SDK Reference entry:
log4net.Appender.TraceAppender.
The following example shows how to configure the TraceAppender to log messages to the System.Diagnostics.Tracesystem. This is the tracing system supplied with the .net base class libraries.See the MSDN documentation for the System.Diagnostics.Traceclass for more details on how to configure the trace system.
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
UdpAppenderFor full details see the SDK Reference entry:
log4net.Appender.UdpAppender.
The following example shows how to configure the UdpAppender to send events to a
RemoteAddress on thespecified
RemotePort.
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<localPort value="8080" />
<remoteAddress value="224.0.0.1" />
<remotePort value="8080" />
<layout type="log4net.Layout.PatternLayout, log4net">
<conversionPattern value="%-5level %logger [%property{NDC}] - %message%newline" />
</layout></appender>
========================================================
下载
Download Apache log4net 1.2.10
log4net 1.2.10 is distributed under the Apache License, version2.0.
log4net has graduated from the Incubator project, however at the time thefollowing releases were made, log4net was still undergoing incubation,therefore these releases are not officially endorsed by the ASF. Futurereleases of log4net will be officially endorsed by the ASF.
The link in the Mirrors column should display a list of available mirrorswith a default selection based on your inferred location. If you do not seethat page, try a different browser. The checksum and signature are links to theoriginals on the main distribution server.
官方网站:
http://logging.apache.org/log4net/index.html