Also used log4net into the log4net (four)

Source: Internet
Author: User
Tags log4net

Reprint Address: http://www.cnblogs.com/dragon/archive/2005/03/24/124254.html

I am the content of other people, I think he wrote very well, so I turned two-thirds of them over.

  

First, the structure of log4net

Log4net has four main components, namely Logger (recorder), Repository (library), Appender (attachment), and layout.

1, Logger

1.1 Logger interface

Logger is the main component that an application needs to interact with, and it is used to generate log messages. The resulting log messages are not displayed directly, and are not output until pre-formatted with layout.

Logger provides several ways to record a log message, you can create multiple logger in your application, and each instantiated logger object is maintained by the Log4net framework as a named entity (named entity). This means that in order to reuse the logger object, you don't have to pass it between different classes or objects, just call it by its name. The Log4net framework uses the inheritance system, which is similar to the inheritance system. The namespaces in the. Net. In other words, if there are two logger, respectively defined as A.B.C and a.b, then we say A.B is the ancestor of A.B.C. Each logger inherits the ancestor's attributes.

The log4net framework defines a ilog interface, and all logger classes must implement this interface. If you want to implement a custom logger, you must first implement this interface. You can refer to a few examples under 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 these methods has an overloaded method to support exception handling. Each overloaded method is shown below, with an additional parameter for the exception type.    void Debug (Object message, Exception ex);  .....  The Boolean property is used to check the log level of the logger//(we will see the log level immediately later)  bool isdebugenabled;  BOOL isinfoenabled;  ... The Boolean property that corresponds to the other method
}

The Log4net framework defines a class called Logmanager that is used to manage all logger objects. It has a getlogger () static method that retrieves an already existing logger object with the name parameter we provide. If the Logger object does not exist in the frame, it will also create a logger object for us. The code looks like this:

Log4net. ILog log = log4net. Logmanager.getlogger ("Logger-name");

In general, we call GetLogger () as a class (type) parameter to keep track of the class we are logging. The type of the passed class (class) can be obtained using the typeof (Classname) method, or it can be obtained using the following reflection method:

System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType

Although the symbols are a bit longer, the latter can be used for a number of occasions, such as the class (type) that gets the calling method.

1.2 Level of the log

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 either method in the program. But in the final release you might not want all the code to waste your CPU cycles, so the framework provides 7 levels and a corresponding Boolean property to control the type of logging.

  

The level has several values

Level

Allowed methods

Boolean property

Priority level

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 log levels for logger

In the Log4net framework, each log object is assigned a log priority level by setting the configuration file. If a log object is not explicitly assigned a level, the object attempts to inherit a level value from his ancestor.

Each method of the Ilog interface has a pre-defined level value. As you can see in table 1, Ilog's Inof () method has an info level. Similarly, the error () method has an error level. When we use either of these methods, the Log4net framework examines the level of logger of the log object and the level of the method. Log requests are accepted and executed only if the level of the method is higher than the log level.

For example, when you create a log object and set his level to info. The framework then sets each Boolean property of the log. When you invoke the appropriate log method, the framework checks the corresponding Boolean property 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 that the log request is passed, we can get the output "message".

For the second method, the level of Debug () is lower than the log level (INFO) of the log object logger, so the log request is rejected and we do not have any output. Similarly, for the third line of statements, we can easily draw a conclusion.

There are two special levels in table 1: All and off. All indicates that all log requests are allowed. Off is to reject all requests.

You can also explicitly check the Boolean property of the Logger object as follows:

if (logger. isdebugenabled)

{

Logger.debug ("message");

}

1.3 Repository

Repository is primarily used to maintain the organizational structure of log objects. In previous versions of Log4net, the framework supported only hierarchical organizational structures (hierarchical organization). This hierarchical structure is essentially an implementation of the library and is defined in log4net. Repository.hierarchy in the name space. To implement a repository, you need to implement log4net. Repository.iloggerrepository interface. However, this interface is not usually implemented directly, but log4net. Repository.loggerrepositoryskeleton is inherited for the base class. The System library (hierarchical repository) is made up of log4net. Repository.Hierarchy.Hierarchy class implementation.

If you are a user of a log4net framework, rather than an extender, you will rarely use the repository class in your code. Instead, you need to use the Logmanager class to automatically manage libraries and log objects.

1.4 Appender

A good log framework should be able to produce multiple destinations of output. For example, output to a console or save to a log file. Log4net can meet these requirements very well. It uses a component called Appender to define the output medium. As the name implies, 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. A complete list of the Appender components provided by Log4net can be found in the Log4net Framework's help manual. With these ready-made appender components, you don't usually have to write them yourself. But if you want, you can do it from log4net. Appender.appenderskeleton class inheritance.

1.5 Appender Filters

A Appender object, by default, passes all log events to the output stream. Appender Filters (Appender Filters) can filter log events according to different criteria. In Log4net. There are already several predefined filters under the filter's namespace. Using these filters, you can filter log events by the log level range, or filter by a particular string. You can find more information about filters in the API's help file.

1.6 Layout

The Layout component is used to display the last formatted output information to the user. Output information can be displayed in a variety of formats, mainly depending on the type of layout component we are using. can be linear or an XML file. The layout component works with a Appender component. A list of the different layout components in the API help manual. A Appender object that can only correspond to one layout object. To implement your own layout class, you need to get from log4net. Layout.layoutskeleton class inherits, it implements the Ilayout interface.

Two. Using Log4net in the program

Before you start logging your program, you need to start the Log4net engine first. This means that you need to first configure the three components mentioned earlier. You can set the configuration in two ways: Setting the configuration in a separate file or defining the configuration in code.

For several reasons, it is recommended to define the configuration in a separate file:

You do not need to recompile the source code to change the configuration;

You can change the configuration when the program is running. This is sometimes important in some web programs and remote procedure calls.

Given the importance of the first approach, let's look at how to set configuration information in a file.

2.1 Defining the configuration file

Configuration information can be placed in one of the following forms of files.

In the program's configuration file, such as Assemblyname.config or Web. config.

In your own file. The file name can be any name you want, such as APPNAME.EXE.XYZ.

The log4net framework looks for the configuration file under the directory path defined relative to the AppDomain.CurrentDomain.BaseDirectory property. The unique identifier that the framework looks for in the configuration file is the <log4net> tag. 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 ref= "Logfileappender"/> <appender-ref ref= "Consol Eappender "/> </root> <logger name=" testapp.logging "> <level value=" DEBUG "/> </logge r> <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]%-5p%c [%x]-%m%n "/> </layout> <filter type= "log4net. Filter. Levelrangefilter "> <param name=" levelmin "value=" DEBUG "/> <param name=" Levelmax "value=" WARN "/ > </filter> </appender> <appender name= "Consoleappender" type= "log4net. Appender.consoleappender "> <layout type=" log4net. Layout.patternlayout "> <param name=" Conversionpattern "value="%d [%t]%-5p%c [%x]-%m%n "/> </lay Out> </appender> </log4net></configuration>

You can copy the above text directly into any program, but it is best to understand how the configuration file is made up. You need to include the <section> configuration node entry in the <configSection> tab only if you need to use the Log4net configuration in the application configuration file. For other individual files, only the text within the <log4net> tag is required, and the order of these labels is not fixed. Here we turn to the meaning of the text in each tag:

2.2 <root>

<root>  <level value= "WARN"/>  <appender-ref ref= "Logfileappender"/>  < Appender-ref ref= "Consoleappender"/></root>

In the framework system, all log objects are descendants of the root log (root logger). Therefore, if a log object is not explicitly defined in the configuration file, the framework uses the properties defined in the root log. In the <root> tab, you can define a list of level and Appender values. If you do not define a level value, debug is the default. The Appender object used by the log object can be defined through the <appender-ref> tag. <appender-ref> declares a reference to a Appender object that is defined elsewhere. Settings in a Logger object override the settings of the root log. For the Appender property, the child log object inherits the Appender list of the parent log object. This default behavior can also be changed by explicitly setting the <logger> tag's Additivity property to False.

<logger name= "testapp.logging" additivity= "false" >

</logger>

The value of additivity is true by default.

2.3 <Logger>

<logger name= "testapp.logging" >  <level value= "DEBUG"/></logger>

The <logger> element pre-defines the settings for a specific log object. You can then retrieve the log with that name by calling the Logmanager.getlogger ("testapp.logging") function. If Logmanager.getlogger (...) When you open a log object that is not a predefined one, the log object inherits the properties of the root log object. Knowing this, we can say that the <logger> tag is not necessary.

2.4 <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]%-5p%c-%m%n"/>  </layout>  <filter type= "log4net. Filter.levelrangefilter ">    <param name=" levelmin "value=" DEBUG "/>    <param name=" Levelmax "value= "WARN"/>  </filter></appender>

The Appender object in the <root> tab or a single <logger> tag can be defined with the <appender> tag. The basic form of the <appender> tag is shown above. It defines the name and type of the Appender. It is also important to have other labels inside the <appender> tag. Different appender have different <param> tags. Here, in order to use Fileappender, you need a filename as a parameter. Another need is to define a layout object inside the <appender> tag. The layout object is defined within its own <layout> tag. The type attribute of the <layout> tag defines the types of layout (in this case, patternlayout) and also determines the parameter values that need to be supplied. Headers and footer tags provide text that is output at the beginning and end of a log session (logging session). Examples of specific configurations for each appender can be obtained in log4net\doc\manual\example-config-appender.html.

2.5 log4net. Conversion Mode in Layout.patternlayout (Conversionpattern)

%M (message): Output log message, such as Ilog.debug (...) A message for the output

%n (New line): NewLine

%d (datetime): Outputs the moment at which the current statement runs

%r (Run time): The number of milliseconds that the output program consumes from running to executing to the current statement

%T (thread ID): The thread ID where the current statement is located

%p: The current priority level of the log, which is debug, INFO, WARN ... such as

%c (Class): The name of the current log object, for example:

The pattern string is:%-10c-%m%n

The code is:

ILog Log=logmanager.getlogger ("Exam.Log");

Log. Debug ("Hello");

The output is in the following form:

Exam.log-hello

%l: The line number where the output statement is located

%F: The file name where the output statement resides

%-Number: Indicates the minimum length of the item and, if not enough, fills it with a space

For example, a conversion mode of%r [%t]%-5p%c-%m%n patternlayout will produce output similar to the following:

176 [main] INFO org.foo.bar-located nearest gas station.

2.6 <filter>

Finally, let's look at the <filter> tag in the Appender element. It defines the filters applied to the Appender object. In this example, we used the Levelrangefilter filter, which records only log events between the log levels specified by the Levelmin and Levelmax parameters. You can define multiple filters (filter) on a appender that filter log events in the order in which they are defined. Information about other filters can be found in the SDK documentation for Log4net.

Also with log4net into Log4net (iv)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.