Select blog from njbaige
Log4net User Guide
1 Overview
1.1 The Advantages of log4net:
Almost all large applications have their own APIs for tracking and debugging. Because onceProgramAfter deployment, 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.
Jing
Verification shows that log records are often an important part of the software development cycle. It has the following advantages: it can provide a precise environment when the application is running, allowing developers to quickly find
Bug; once the log is added to the program
OutputCodeThe 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:
You can downloadSource code. 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
You can use multiple methods to record a log message. You can create multiple logger in your application. Each instantiated logger object is named by the log4net framework.
(Named
Entity. 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. Log4net framework
The inheritance system 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 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
}
Log4net
The Framework defines a class called logmanager to manage all the logger objects. It has a static getlogger () method that uses the name parameters we provide to retrieve
The existing logger object. 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
Zheng
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. But in the final release, you may not want to waste all the code.
Therefore, the Framework provides seven levels and corresponding Boolean attributes to control the log record type.
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.
Ilog
Each method of the interface has a pre-defined level value. As you can see in Table 1, the ilog inof () method has the info level. Likewise, and so on, the error () method
Has an error level. When we use any of the preceding methods, the log4net framework checks the logger level and method level of the log object. Only when the method level is higher than the Log Level
The log request is accepted and executed.
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
It is mainly used to maintain the organizational structure of log objects. In earlier versions of log4net, the framework only supports hierarchical organization structures (hierarchical
Organization ). This hierarchical structure is essentially an implementation of the library and is defined in log4net. repository. Hierarchy
Namespace. To implement a repository, you must implement log4net. repository. iloggerrepository
Interface. However, this interface is not directly implemented, but inherited based on the log4net. repository. loggerrepositoryskeleton class. System
Library (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
I
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
These requirements can be well met. 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. For a complete list of appender components provided by log4net, refer to the log4net framework help manual.
To. With these ready-made appender components, you generally do not have to write them yourself. But if you want to, you can
The log4net. appender. appenderskeleton class inherits.
2.4 appender Filters
I
Appender objects pass all log events to the output stream by default. Appender filter (appender filters)
Log events can be filtered according to different standards. There are several predefined filters in the log4net. Filter namespace. With these filters, you can filter logs by log level.
Log events, or filter by a special string. You can find more information about the filter in the Help file of the API.
2.5 Layout
Layout
The 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. One appender object can only correspond to one
Layout object. To implement your own layout class, you need to inherit from the log4net. layout. layoutskeleton class, which implements 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. leleappender">
<Layout type = "log4net. layout. patternlayout">
<Param name = "conversionpattern"
Value = "% d [% T] %-5 p % C [% x]-% m % N"
/>
</Layout>
</Appender>
</Log4net>
</Configuration>
You
You can directly copy the above text to any program, but it is better to understand how the configuration file is made up.
Only when you need to use log4net configuration in the application configuration file, you need to add the <configsection> label <
Section> Configure the node entry. For other separate files, only the text in the <log4net> label is required, and the order of these labels is not fixed. Lower
In turn, we will explain the meaning of the text in each label:
3.1.1 <root>
<Root>
<Level value = "Warn"/>
<Appender-ref = "logfileappender"/>
<Appender-ref = "leleappender"/>
</Root>
In
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 level value and
List of appender. If no level value is defined, the default value is debug. You can use the <appender-ref> label to define
Appender object. <Appender-ref> declares a reference to the appender object defined elsewhere. Set in a logger object
Will overwrite the root log settings. For the appender attribute, the sub-log object inherits the appender list of the parent log object. This default behavior can also be explicitly set
<Logger> the additivity attribute of a tag is changed 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
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. Knowing this,
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>
In <
The root> tag or the appender object in a single <logger> tag can be defined using the <appender> tag. <
The basic format of appender> 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. In this case
With 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
Is patternlayout), and the parameter value to be provided is also determined. The header and footer labels provide a log SESSION (Logging
Session. For specific configuration examples of each appender, you can go to log4net \ doc \ manual \ example-
In the 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>
Most
Next, let's look at the <filter> tag in the appender element. It defines the filter applied to the appender object. In this example, we use
The levelrangefilter can only record log events between the log level specified by the levelmin and levelmax parameters. You can
Multiple filters are defined on the appender. These filters filter log events in the order they are defined. Information about other filters can be found in
In the 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
Yes
Outputs log information in several ways using ilog. You can also check the Boolean variable isxxxenabled before calling a method, and then decide whether to call the function that outputs log information.
High 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. leleappender (
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.
Log4net. config. basicconfigurator
Class uses the static method configure to set an appender
Object. The constructor of appender requires the layout object accordingly. You can also directly call basicconfigurator. Configure without parameters.
(), Which 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
Enable
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. Same
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.