From: http://blog.5d.cn/vip/icecream/200511/185284.html
Many developers want a very powerfulProgramThe log management library can be used to understand the usage of applications. When a program encounters a problem, you can analyze the log to understand the problem.
In the past, we always used a very simple way to process logs. That is, when a log file is used, users are required to provide the file when there is a problem with the program. However, log files are often deleted or not missing.
Log4net is part of the famous log4j for Java project. It is composed
Www.neoworks.com
Developed by a team that supports multiple log methods. Such as ADO (ms SQL Server, etc.), file (file), console (console), EventLog (System Log), SMTP (Mail method )...
It also supports all. Net platforms:
Microsoft. NET Framework 1.0 (1.0.3705)
Microsoft. NET Framework 1.1 (1.1.4322)
Microsoft. NET Compact Framework 1.0 (1.0.5000)
Mono 0.25 or higher (in Linux)
Microsoft Shared Source CLI 1.0 (MS Development)Source code. Net Runtime Library)
For more details:
Log4net site for Apache
(Official site of log4net)
Using log4net
(This is a very professional guide, which is translated below)
Log4net. dll
(The compiled log4net. dll file can be directly added to your project .)
Log4net User Guide
1 Overview
1.1 The Advantages of log4net:
Almost all large applications have their own APIs for tracking and debugging. Once a program is deployed, it is unlikely that special debugging tools will be used. However, an administrator may need a powerful log system to diagnose and fix configuration problems.
It has been verified that log records are often an important part of the software development cycle. It has the following advantages: it provides a precise environment when the application is running, allowing developers to locate bugs in the application as soon as possible; once the log output is added to the programCodeThe program can generate and output log information while running the program without manual intervention. In addition, log information can be output to different places (such as the console and files) for future research.
Log4net is a log record package designed for this purpose and used in the. NET development environment.
1.2 installation of log4net:
Users can download the source code of log4netfrom http://logging.apache.org/log4net. After the package is decompressed, load log4net. sln to Visual Studio. NET in the decompressed src directory. After compilation, you can obtain log4net. dll. To add the log function to your program, you only need to introduce log4net. DLL into the project.
2 log4net Structure
Log4net has four main components: logger, repository, appender, and layout ).
2.1 Logger
2.1.1 logger interface
Logger is the main component for applications to interact and is used to generate log messages. The generated log messages are not directly displayed. They must be formatted by layout before being output.
Logger provides multiple methods to record a log message. You can create multiple logger in your application. Each instantiated logger object is named as a nameentity (Named Entity) by the log4net framework). This means that in order to reuse a logger object, you do not have to pass it between different classes or objects. You just need to call it with its name as a parameter. The log4net framework uses an inheritance system, which is similar to the namespace in. net. That is to say, if there are two logger defined as A. B. C and A. B, then we say a. B is the ancestor of A. B. C. Each logger inherits the attributes of the ancestor.
The log4net Framework defines an ilog interface, which must be implemented by all logger classes. If you want to implement a custom logger, you must first implement this interface. You can refer to several examples in the/extension directory.
The ilog interface is defined as follows:
Public interface ilog
{
Void debug (Object message );
Void Info (Object message );
Void warn (Object message );
Void error (Object message );
Void fatal (Object message );
// Each of the preceding methods has an overloaded method to support exception handling.
// Every overload method is shown as follows, with an additional parameter of the exception type.
Void debug (Object message, exception ex );
//...
// Boolean attribute is used to check the log level of logger
// (We will see the log level later)
Bool isdebugenabled;
Bool isinfoenabled;
//... Boolean attribute corresponding to other methods
}
The log4net Framework defines a class called logmanager to manage all logger objects. It has a static getlogger () method that uses the name parameters we provide to retrieve existing logger objects. If this logger object does not exist in the framework, it will also create a logger object for us. The Code is as follows:
Log4net. ilog log = log4net. logmanager. getlogger ("logger-name ");
Generally, we call getlogger () with the type of the class as the parameter to track the classes that we are logging. The passed class type can be obtained using the typeof (classname) method, or the following reflection method can be used:
System. reflection. methodbase. getcurrentmethod (). declaringtype
Although the symbol is longer, the latter can be used for some occasions, such as obtaining the type of the class that calls the method ).
2.1.2 Log Level
As you can see in the ilog interface, there are five different ways to track an application. In fact, these five methods work on different log priority levels set by the logger object. These different levels are defined as constants in the log4net. SPI. level class. You can use any method in the program. However, in the final release, you may not want all the code to waste your CPU cycle. Therefore, the Framework provides seven levels and corresponding Boolean attributes to control log record types.
Level has the following values:
Level
Allowed methods
Boolean attribute
Priority
Off
Highest
Fatal
Void fatal (...);
Bool isfatalenabled;
Rror
Void error (...);
Bool iserrorenabled;
Warn
Void warn (...);
Bool iswarnenabled;
Info
Void Info (...);
Bool isinfoenabled;
Debug
Void debug (...);
Bool isdebugenabled;
All
Lowest
Table 1 logger Log Level
In the log4net framework, by setting the configuration file, each log object is assigned a log priority level. If a log object is not explicitly assigned a level, the object tries to inherit a level value from its ancestor.
Each method of the ilog interface has a pre-defined level value. As you can see in Table 1, the ilog inof () method has the info level. Similarly, the error () method has the error level. When we use any of the preceding methods, the log4net framework checks the logger level and method level of the log object. Log requests are accepted and executed only when the method level is higher than the log level.
For example, when you create a log object and set its level to info. Therefore, the Framework sets each Boolean attribute of the log. When you call a log method, the Framework checks the corresponding Boolean attribute to determine whether the method can be executed. The following code:
Logger. Info ("message ");
Logger. debug ("message ");
Logger. Warn ("message ");
For the first method, the level of Info () and the log level (Info), so the log request will be passed, and we can get the output result "message ".
For the second method, the debug () level is lower than the log level (Info) of the log object logger. Therefore, the log request is rejected and we cannot get any output. Similarly, we can easily draw conclusions for the third line of statements.
Table 1 has two special levels: All and off. All indicates that all log requests are allowed. Off is used to reject all requests.
You can also explicitly check the Boolean attribute of the logger object, as shown below:
If (logger. isdebugenabled)
{
Logger. debug ("message ");
}
2.2 Repository
Repository is mainly used to maintain the organizational structure of log objects. In earlier versions of log4net, the framework only supports hierarchical organization ). This hierarchical structure is essentially an implementation of the database and is defined in the log4net. repository. Hierarchy namespace. To implement a repository, you must implement the log4net. repository. iloggerrepository interface. However, this interface is not directly implemented, but inherited based on the log4net. repository. loggerrepositoryskeleton class. Hierarchical repository is implemented by the log4net. repository. hierarchy. Hierarchy class.
If you are a log4net framework user, rather than an extension, you will hardly use the repository class in your code. Instead, you need to use the logmanager class to automatically manage databases and log objects.
2.3 appender
A good log framework should be able to generate multi-destination output. For example, output to the console or save to a log file. Log4net can meet these requirements. It uses a component called appender to define the output media. As shown in the name, these components attach them to the logger log component and pass the output to the output stream. You can attach multiple appender components to a log object. The log4net framework provides several appender components. You can find the complete list of appender components provided by log4net in the log4net framework help manual. With these ready-made appender components, you generally do not have to write them yourself. But if you want to, you can inherit from the log4net. appender. appenderskeleton class.
2.4 appender Filters
An appender object transmits all log events to the output stream by default. Appender filters can filter log events according to different standards. There are several predefined filters in the log4net. Filter namespace. With these filters, you can filter log events by log level or by a special string. You can find more information about the filter in the Help file of the API.
2.5 Layout
The layout component is used to display the last formatted output information to the user. The output information can be displayed in multiple formats, mainly dependent on the layout component type we use. It can be a linear or XML file. The layout component works with an appender component. The API help manual contains a list of different layout components. An appender object can correspond to only one layout object. To implement your own layout class, you need to inherit from the log4net. layout. layoutskeleton class, which implements the ilayout interface.
3. Use log4net in the program
Before logging your program, you must start the log4net engine. This means you need to configure the three components mentioned above. You can set the configuration in two ways: Set the configuration in a separate file or define the configuration in the code.
We recommend that you define the configuration in a single file for the following reasons:
L you can change the configuration without re-compiling the source code;
L you can change the configuration when the program is running. This is sometimes important in some web programs and remote process calls;
Considering the importance of the first method, Let's first look at how to set configuration information in the file.
3.1 define the configuration file
The configuration information can be stored in one of the following format files.
In the configuration file of the program, such as assemblyname. config or web. config.
In your own file. The file name can be whatever you want, such as appname.exe. XYZ.
The log4net framework searches for the configuration file in the directory path defined by the appdomain. currentdomain. basedirectory attribute. The <log4net> tag is the unique identifier of the Framework in the configuration file. An example of a complete configuration file is as follows:
<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>
<Configsections>
<Section name = "log4net" type = "log4net. config. log4netconfigurationsectionhandler, log4net-net-1.0"/>
</Configsections>
<Log4net>
<Root>
<Level value = "Warn"/>
<Appender-ref = "logfileappender"/>
<Appender-ref = "leleappender"/>
</Root>
<Logger name = "testapp. Logging">
<Level value = "debug"/>
</Logger>
<Appender name = "logfileappender" type = "log4net. appender. fileappender">
<Param name = "file" value = "log-file.txt"/>
<Param name = "appendtofile" value = "true"/>
<Layout type = "log4net. layout. patternlayout">
<Param name = "Header" value = "[header] \ r \ n"/>
<Param name = "footer" value = "[footer] \ r \ n"/>
<Param name = "conversionpattern" value = "% d [% T] %-5 p % C [% x]-% m % N"/>
</Layout>
<Filter type = "log4net. Filter. levelrangefilter">
<Param name = "levelmin" value = "debug"/>
<Param name = "levelmax" value = "Warn"/>
</Filter>
</Appender>
<Appender name = "leleappender" type = "log4net. appender. consoleappender">
<Layout type = "log4net. layout. patternlayout">
<Param name = "conversionpattern" value = "% d [% T] %-5 p % C [% x]-% m % N"/>
</Layout>
</Appender>
</Log4net>
</Configuration>
You can directly copy the above text to any program, but it is better to understand how the configuration file is made up. You must add the <section> Configuration node entry to the <configsection> tab only when you need to use log4net configuration in the application configuration file. For other separate files, only the text in the <log4net> label is required, and the order of these labels is not fixed. Next we will explain the meaning of the text in each label in sequence:
3.1.1 <root>
<Root>
<Level value = "Warn"/>
<Appender-ref = "logfileappender"/>
<Appender-ref = "leleappender"/>
</Root>
In the framework system, all log objects are descendants of root logger. Therefore, if a log object is not explicitly defined in the configuration file, the framework uses the attributes defined in the root log. In the <root> label, you can define the list of level values and appender. If no level value is defined, the default value is debug. You can use the <appender-ref> label to define the appender object used by the log object. <Appender-ref> declares a reference to the appender object defined elsewhere. Setting in a logger object overwrites the setting of the root log. For the appender attribute, the sub-log object inherits the appender list of the parent log object. This default behavior can also be changed by explicitly setting the additivity attribute of the <logger> label to false.
<Logger name = "testapp. Logging" additivity = "false">
</Logger>
The default value of additivity is true.
3.1.2 <logger>
<Logger name = "testapp. Logging">
<Level value = "debug"/>
</Logger>
<Logger> the element predefines the setting of a specific log object. Then, by calling the logmanager. getlogger ("testapp. Logging") function, you can check the logs with this name. If logmanager. getlogger (...) If the log object is not a predefined log object, the log object inherits the attributes of the root log object. With this in mind, we can say that the <logger> label is not necessary.
3.1.3 <appender>
<Appender name = "logfileappender" type = "log4net. appender. fileappender">
<Param name = "file" value = "log-file.txt"/>
<Param name = "appendtofile" value = "true"/>
<Layout type = "log4net. layout. patternlayout">
<Param name = "Header" value = "[header] \ r \ n"/>
<Param name = "footer" value = "[footer] \ r \ n"/>
<Param name = "conversionpattern" value = "% d [% T] %-5 p % C-% m % N"/>
</Layout>
<Filter type = "log4net. Filter. levelrangefilter">
<Param name = "levelmin" value = "debug"/>
<Param name = "levelmax" value = "Warn"/>
</Filter>
</Appender>
You can use the <appender> label to define the appender object in the <root> label or a single <logger> label. <Appender> the basic format of the tag is shown above. It defines the appender name and type. What's more important is other labels inside the <appender> tag. Different appender have different <param> labels. Here, to use fileappender, you need a file name as the parameter. You also need to define a layout object within the <appender> tag. The layout object is defined in its own <layout> label. <Layout> the type attribute of a tag defines the layout type (in this example, patternlayout) and the parameter values to be provided. The header and footer labels provide the text output at the beginning and end of a log SESSION (logging session. Examples of specific configurations for each appender can be obtained in the log4net \ doc \ manual \ example-config-appender.html.
3.1.4 conversionpattern)
% M (Message): the output Log message, such as ilog. debug (...) Output Message
% N (New Line): line feed
% D (datetime): time when the current statement is output
% R (Run time): number of milliseconds consumed by the output program from running to executing to the current statement
% T (thread ID): ID of the thread where the current statement is located
% P (priority): Current Log priority level, namely debug, info, warn... And so on
% C (class): name of the current log object, for example:
Mode string: %-10C-% m % N
Code:
Ilog log = logmanager. getlogger ("exam. Log ");
Log. debug ("hello ");
The output is in the following format:
Exam. Log-Hello
% L: the row number of the output statement
% F: File Name of the output statement
%-Number: indicates the minimum length of the item. If not, fill it with spaces.
For example, patternlayout in the conversion mode of % R [% T] %-5 p % C-% m % N will generate output similar to the following:
176 [main] info org. Foo. Bar-located nearest gas station.
3.1.5 <filter>
Finally, let's look at the <filter> tag in the appender element. It defines the filter applied to the appender object. In this example, the levelrangefilter is used to record only log events between the log levels specified by the levelmin and levelmax parameters. You can define multiple filters on an appender. These filters filter log events in the order they are defined. Information about other filters can be found in the log4net SDK documentation.
3.2 use the configuration file
3.2.1 associate the configuration file
After we create the preceding configuration file, we need to associate it with our application. By default, each independent executable Assembly defines its own configuration. The log4net framework uses log4net. config. domconfiguratorattribute to define the configuration file at the Assembly level.
For example, you can add the following statement to the assemblyinfo. CS file of the project.
[Assembly: log4net. config. domconfigurator (configfile = "FILENAME ",
Configfileextension = "Ext", watch = true/false)]
L configfile: Specifies the path and file name of our configuration file, including the extension.
L configfileextension: If we use different file extensions for the compiled Assembly, we need to define this attribute. By default, the assembly configuration file extension is "Config ".
L watch (Boolean attribute): This attribute is used by the log4net framework to determine whether to monitor file changes during runtime. If this attribute is true, filesystemwatcher will be used to monitor file changes, renaming, deletion, and other events.
Where: configfileand configfileextensionextension cannot be used at the same time. configfileindicates the name of the configuration file. For example, configfileextension must be config.txt"
Break ";
You can also apply domequalatio () without parameters ():
[Assembly: log4net. config. domconfigurator ()]
You can also use the domconfigurator class in the program code to open the configuration file. Class constructor requires a fileinfo object as a parameter to indicate the configuration file name to be opened. This method is the same as setting properties in the Assembly to open a configuration file.
Log4net. config. domconfigurator. Configure (
New fileinfo ("testlogger. EXE. config "));
The domconfigurator class also provides the configureandwatch (...) method to configure the framework and detect file changes.
The above steps summarize the configuration-related aspects. Next we will use the logger object in two steps.
3.2.2 create or retrieve log objects
Log objects use the attributes defined in the configuration file. If a log object is not defined in the configuration file in advance, the Framework obtains the attributes of the ancestor Node Based on the inheritance structure, and finally obtains the attributes from the root log. As follows:
Log4net. ilog log = log4net. logmanager. getlogger ("mylogger ");
3.2.3 output log information
You can use several methods of ilog to output log information. You can also check the Boolean variable isxxxenabled before calling a method, and then decide whether to call the function that outputs log information, so as to improve the program performance. Because the framework is calling ilog. debug (...) When such a function is used, it first determines whether the level log level conditions are met.
If (log. isdebugenabled) log. debug ("message ");
If (log. isinfoenabled) log. Info ("message );
3.3 configure log4net in the program
In addition to using a configuration file to configure log4net, you can also use code in the program to configure the log4net framework. Example:
// Use fileappender with patternlayout
Log4net. config. basicconfigurator. configure (New log4net. appender. fileappender (New log4net. layout. patternlayout ("% d [% T] %-5 p % C [% x]-% m % N"), "testfile. log "));
// Using a fileappender with an xmllayout
Log4net. config. basicconfigurator. Configure (New log4net. appender. fileappender (New log4net. layout. xmllayout (), "testfile. xml "));
// Using a consoleappender with a patternlayout
Log4net. config. basicconfigurator. configure (New log4net. appender. consoleappender (New log4net. layout. patternlayout ("% d [% T] %-5 p % C-% m % N ")));
// Using a consoleappender with a simplelayout
Log4net. config. basicconfigurator. Configure (New log4net. appender. leleappender (New log4net. layout. simplelayout ()));
Although it is convenient to configure log4net with code, you cannot configure each log object separately. All these configurations are applied to the root log.
The log4net. config. basicconfigurator class uses the static configure method to set an appender object. The constructor of appender requires the layout object accordingly. You can also directly call basicaggregator. Configure () without parameters. It uses a default patternlayout object to output information in a leleappender. As follows:
Log4net. config. basicconfigurator. Configure ();
The following format is displayed during output:
0 [1, 1688] Debug log1 a B C-test
20 [1, 1688] info log1 a B C-test
After the log4net framework is configured, you can use the log function as described earlier.
4. Summary
With log4net, you can easily add the log function to the application. With log4net, You can precisely control the output of log information, reduce unnecessary information, and improve log record performance. At the same time, with the external configuration file, you can change the log behavior of the application without re-compiling the program, so that you can flexibly select the information to be recorded based on the situation.