Document directory
The usage of log4net can be summarized as follows:
L add class library reference
Add the log4net class library to the program reference.
L specify the configuration name. 2. Specify the file name.
[Assembly: log4net. Config. XmlConfigurator (ConfigFile = ". log4net. config", Watch = true)]
2. Method of specifying the extension
[Assembly: log4net. Config. XmlConfigurator (ConfigFileExtension = "log4net", Watch = true)]
Whether the configuration file of log4net is independent or mixed in web. config depends on the value passed by the ConfigFile parameter above.
// Summary:
// Gets or sets the filename of the configuration file.
//
// Remarks:
// If specified, this is the name of the configuration file to use with
// 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 wocould 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 ;}
Note: This configuration file should have the System. AppDomain. BaseDirectory directory (usually the same as web. config ).
Whether it is based on the file name or the extension. After reading the attribute comments in log4net, I think you are very clear.
Either way, you must specify the name or extension of the configuration file in the program code. In addition, no matter the method above, you need to put this line of code in the project code. It is generally recommended to store it in Properties \ AssemblyInfo. cs, of course, it can also be placed in other code.
I tried to put it in Global. asax. cs and found that it could also work.
Note:
This "Watch = true" parameter indicates whether log4net re-loads new configuration data after the configuration file content is changed.
Follow the notes in the log4net Class Library:
//
// 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 ;}
From the preceding notes, we can understand that the Watch switch can monitor configuration file changes. Therefore, we are not suitable to mix log4net configurations into web. config. It turned out to be simple. The web. config changes the database connection string, and the configuration data will be reloaded.
There are two reference documents (some of which may be inaccurate) for the above content. They are only for reference and cannot be used as "golden rule ":
Http://www.codeproject.com/KB/dotnet/ConfigureLog4Net.aspx
Http://blog.csdn.net/aspnet2002web/article/details/6046655
L add content in the configuration file 2 reference the configuration
Whether in web. config or another configuration file, the following content must exist:
1. The root must be: <configuration>
2. Add the following content in <configSections> under <configuration>.
<Section name = "log4net" type = "log4net. Config. Log4NetConfigurationSectionHandler, log4net"/>
3. The following describes the specific configuration items in log4net.
From my experiment results, if the file extension is specified, the content of 1 and 2 above can be removed. That is, in an independent configuration file, the root node of xml can be <log4net> directly. The principle has not been fully understood yet.
2. Brief Introduction to various Appender
Log4net has a variety of built-in Appender
Appender is the most important part in log4net configuration. Generally, each appender represents a log output medium, such as log files, EvengLog, database, console, mail, Trace, ASP.. NET page.
This article provides examples for various built-in appender configurations, but it is far from detailed. For more information about the parameters and options of each appender, see the appender SDK documentation.
U Appender can be customized by yourself.
Find the SDK and SDK instructions on the official website.
U Appender, which is non-exclusive by default.
That is, logs can be sent to multiple Appender simultaneously. For example, you can either output data to the Console or write data to a text file, or write data to a standard database (Oracle, SQLServer, Access, etc.
Can logs be written to text files in XML format? It should be okay. How can I configure it?
The following is my previous Console (Console) and log output to text files.
For more information about various Appender, I am not prepared to write all the text here (not at half past one). I have found several excellent articles here:
Two articles from the official website:
Http://logging.apache.org/log4net/release/config-examples.html
Http://logging.apache.org/log4net/release/sdk/log4net.Appender.html
Another article from technical blog:
Http://www.beefycode.com/post/Log4Net-Tutorial-pt-3-Appenders.aspx
Download the built-in Appender class published on the official website:
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 shoshould be displayed. |
AppenderCollection |
A stronugly-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 shoshould be displayed. |
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 shoshould be displayed. |
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 shocould be logged. |
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 shocould be logged. |
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 multicast Rams to a remote host or a multicast group using an UdpClient. |
2. Which Appender functions are specified in Root?
2 <root>
2 <level value = "WARN"/>
2 <appender-ref = "LogFileAppender"/>
2 <appender-ref = "ConsoleAppender"/>
2 <appender-ref = "NetSendAppender"/>
2 </root>
The value specified by "ref" is the name defined for various Appender above. Note that it is not the Appender class name.
2. Declare the logger classification levels in the configuration file.
2 <! -- Specify the level for some specific categories -->
2 <logger name = "ProjectManagement">
2 <level value = "ALL"/>
2 <appender-ref = "LogFileAppender"/>
2 </logger>
L call log4net code
Code calling is roughly like this:
Add reference using log4net;
L private static readonly ILog logger = LogManager. GetLogger ("ProjectManagement ");
L record any information, including exceptions
L logger. Error (Server. GetLastError ());
Details about how to use LogManager. GetLogger:
The following content is extracted from the comments of the class library.GetLoggerThis method has multiple overload parameters. For more information, see the class library annotations.
//
// 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 );
Attachment
Two. cs codes in this file:
Log4net. Config. XmlConfiguratorAttribute. cs
Log4net. LogManager. cs
These two files are the prototype definitions of related classes in the log4net class library, including annotations.