Chinese documentation in log4j

zhaozj2021-02-16  72

Translator statement:

1. This is a manual translation of the development of the document according to the latest log4j (Jakarta-Log4j-1.2.8).

2. Translators try their best to keep the original format so that the reader find the original text

3. For some keywords, there is a text word, easy to read

4. The original words are more uncommon, and the translators are referring to Jinshan Words, and the combination of the found is maintained in the original text.

5. For the comparative statement, the translator tries to use the method of translation while maintaining the original text.

6. There are several places to discuss the in-depth discussion of log4j knowledge, translation is not very good, will be revised later

Wang Jian

2004.6.18

Translation:

Copyright 2000-2002Apache Software Organization. Retain all rights. This software is released under the protection of the Apache Software License 1.1 version. The content of this protocol is included in the license.txt file with LOG4J. This document is based on the "Log4j Delivers Control Over Logging" article published by JavaWorld in November 2000. However, this article is currently more detailed and recent information. This article also borrowed some content from the "The Complete Log4j Manual" of the same author.

Summary

This article describes the Log4J's API, unique features and design principles. Log4j is an open source software project that gathered many author labor results. It allows developers to output log description information in any granularity. It utilizes external configuration files that are fully configurable at runtime. The most powerful thing is that log4j has a smooth learning curve. Beware: From the feedback from the user, it is very addictive.

Introduction

Almost every large application contains its own log record or tracking the API. Consistent with this principle, E.U. Semper project decided to write your own tracking API. This happened in 1996. After several improvements, after several evolution and a large amount of work gradually became log4j, a popular Java log package. This package is released under the protection of the Apache software license, and the open source organization initiative guarantees that this is a complete open source license. The latest log4j version contains source code, class files, and documents that can be found at http://jakarta.apache.org/log4j/. By the way, Log4j has been developed to C, C , C #, Perl, Python, Ruby, and Eiffel language.

Inserting a log description code in your code is a low-level debugging method. This may be unique because the debugger is not always available or applicable. This is a very common phenomenon on multi-threaded applications and distributed applications.

Experience shows that the log is an important component in the development link. It provides a lot of a bit. For a running application, it provides accurate environmental information. Once the code is inserted, the log output does not need to be interference. Also, log output can be saved in a permanent media for later research. Including it in development links, an efficient functional log package can be seen as an audit tool.

Just like Brian W. Kernighan and Rob Pike wrote in their "Programming Practice"

In view of the choice of everyone, we do not advocate the use of the debugger unless the value of a variable is obtained in order to track the stack or get a variable. One reason is that it is easy to lose details in complex data structures and control flows; the second reason is that we find that single-step tracking a program and careful thinking and adding code output descriptions compared to self-inspection. There is no efficiency. See all description information will take more time than the information outputted by the scan correct place. Decide that the key placement output print statement is more time-saving than single step, even if we know where it is. It is important that the debug statement is set with the program; and the debugging session is temporary.

The log code has its own shortcomings. It may cause the application to run slow down. If the output is too detailed, it may cause screen flashback (Scrolling Blindness). To mitigate these effects, log4j is designed to be dependent, faster and scalable. Since the log is very small is the focus of the application, the log4j API strives to make simple and easy to understand and use. Loggers, Appenders and Layout (Layouts)

Log4j contains three primary components: recorders, output sources, and layouts. These three types of components work together to output messages by category and grades of messages, and control how these messages are formatted and output when running.

Recorder level

Any Log4J API's biggest advantage is that System.out.Println is inherently capable of allowing other people to do not work if others are not obstructed. This ability is assumed that the log space is all the space of all possible log statements, which can be classified according to the developer's standard. This observation data has previously guided us to choose categories as the center concept of the package. However, since the LOG4J version 1.2, the logger class has replaced the Category class, and the recorder (Logger) class can be considered just a range (category) class. Alias.

The logger is named entity (logger), a logger name is an event-sensitive, and they follow the hieranchical naming rules:

Name the name of a logger, if the name of a recorder follows a "." Number that is considered to be a subcorder prefix, then it is considered another recorder ancestor

For example, a recorder named "com.foo" is the father name "com.foo.bar". Similarly, "java" is "java.util" father, is a ancestor "java.util.Vector". This naming rule should be very familiar to most developers.

Root logger is at the top of the recorder level. In both cases, it is unexpected.

1. It always exists

2. It does not get the name

The static method of calling class logger.getrootLogger gets root classes. All other classes are instantiated, and these instances are obtained using the static method Logger.getLogger with class. This method uses the desired recorder as a parameter. Some basic methods for recorders are as follows:

Package org.apache.log4j;

Public class logger {

// Creation & Retrieval Methods: Public Static Logger getRootLogger (); public static logger getlogger (String name);

// printing methods: public void debug (Object message); public void info (Object message); public void warn (Object message); public void error (Object message); public void fatal (Object message);

// generic printing method: public void log (level L, Object Message);

The recorder can be set level. Possible levels include Debug, Info, Warn, Error and Fatal, which are defined in the org.apache.log4j.level class. Although we don't encourage, you can also define your own level through a subclass level class. A better way will introduce it later if a given logger is not set level, it can integrate a nearest ancestor with a specified level. More authentic:

Level Inheritance level inherits the level of inheritance is specified to the recorder class C, which is equal to the first non-empty level in the recorder level.

In order to ensure that all recorders can eventually inherit a level, the root recorder always has a specified recorder.

The following is four tables that have different specified level values ​​and refer to the inheritance level of the above rules.

Recorder name

Specified level

Inherited level

root

Propot

Propot

X

None

Propot

X.y

None

Propot

X.y.z

None

Propot

Example 1

In the example 1 above, only the root recorder is specified. This level of value is ProT, which is inherited by other recorders x, x.y and x.y.z

Recorder name

Specified level

Inherited level

root

Propot

Propot

X

PX

PX

X.y

PXY

PXY

X.y.z

PXYZ

PXYZ

Example 2

All recorders in Example 2 have a specified level value, which is not necessary to inherit the level value.

Recorder name

Specified level

Inherited level

root

Propot

Propot

X

PX

PX

X.y

None

PX

X.y.z

PXYZ

PXYZ

Example 3

In Example 3, all recorders, including x and x.y.z, are specified by specifying the recorder value of ProT, PX, and PXYZ. Recorder x.y inherits its level value from its parent X

Recorder name

Specified level

Inherited level

root

Propot

Propot

X

PX

PX

X.y

None

PX

X.y.z

None

PX

Example 4

In Example 4, the recorder root and x were specified by the specified level value as ProT and PX, respectively. Recorder x.y and x.y.z inherit their level value from the parent X closest to their, this parent has a specified level value ...

The log request is processed by calling a print method of a logger instance. These print methods are Debug, Info, Warn, Error, Fatal, and Log.

By defining, the printing method determines the level of a log request. For example, if c is a log instance, statement C.info ("..") is a log request with an INFO level.

If the level of the log request is equal to or greater than the level of the log recorder, then this log request is feasible. Instead, the request will not be output. A logger that is not specified level will inherit from hierarchy. These rules are summarized below.

Basic selection rules are in a Q-level log recorder (specified and inherited) has a log request with a P level, if P> = Q, this log request can be output.

This rule is the core of log4j. Assuming level is sorted, the level of the standard, we set DEBUG

// Get a logger instance named "com.foo" logger logger = logger.getlogger ("com.foo");

// Now set its level Normally you do not need to set the // level of a logger programmatically This is usually done // in configuration files logger.setLevel (Level.INFO);... Logger barlogger = Logger.getLogger ( " com.foo.bar ");

// this Request is enabled, Because Warn> = info. Logger.warn ("Low Fuel Level.");

// this Request is disabled, because debug

///// ' "" LOCATED NEAREST GAS Station. ");

// this request is disabled, Because Debug

Calling the getLogger method with the same name will return a reference to the same recorder object

E.g,

Logger x = logger.getlogger ("wombat"); logger y = logger.getlogger ("wombat");

X and Y point to the same log logger object

Therefore, configuring a logging device, which is possible to obtain the same instance without the conversion reference in the code. Inside the basic contradiction of the biological father's era, you can always create and configure them according to certain rules. In particular, even if a "parent" log recorder is instantiated behind its descendants, it still finds and connects to its descendants.

When the application is initialized, the configuration of the log4j is executed. The best way is to read a configuration file. Soon discussed this method

By using software components, log4j is easy to name log recorders. This can be done by static instantiation logging in each class, and the logger name is the same as the complete class name. This is a useful way to define the log recorder directly. Since the log output has the name of the log recorder that generates the log, the naming policy makes the source of identifying the log message. However, this is just a possibility, although the strategy of Naming Day recorder is very ordinary, Albeit Common, Strategy for Naming Loggers. Log4j does not constrain log recorder possible trend (Log4j Does NOT RESTRICT The Possible Set of Loggers). Developers can name the log recorder as needed.

However, named logging in the class seems to be the best strategy you know now.

Output source and layout

Based on the log recorder selectively allows the log request to work only a part of the Picture .log4j allows the log request to output to multiple targets. In the Log4j statement, the output destination is an output source. Recently, the output source includes control, file, GUI component, remote socket server (Remote socket Servers), JMS, NT event logger (NT Event loggers) and Remote Unix Syslog Daemons. It can also record the log asynchronously. A log recorder can have multiple output sources.

The AddAppender method adds an output source to a given log recorder. Corresponding to a given log recorder will be turned to all output sources because these output sources are higher levels of outputs in hierars. In other words, the output source is an Additional Logger Hierarchy that is inherited from the hierarchy of the log recorder. For example, if there is a console output source being added to a root logger (ROOT Logger), the last activated log request will be printed on the console, in addition, if a file output source is added to the log recorder. , Called C, then activate the log request of children C and C will output to a file and console. Overlying this default behavior is possible to facilitate the setting of the additional identifier as a false, the aggregation of the output source is no longer additional.

The rules for managing output source additional behavior will be summarized below.

The output source of the additional feature log recorder C's log statement will be directed to all of C and all of its ancestors. This is the intention of the provision "Appender Additive". However, if there is a ancestor of the logger C, it is called P. There is an additional identifier being set to false, and then the output of C will be oriented to C. And all output sources from the ancestors P (including P), but does not include any output source in P's ancestors. The log recorder has its own additional characteristics, which is set by default to True

The following table shows an example:

Log recorder

Added output source

Additional feature logo

Output goal

comment

root

A1

NOT Applicable

A1

The root logger is anonymous, but can be accessed with the logger.getrootlogger () method. The root logger does not have the default output source.

x

A-X1, A-X2

True

A1, A-X1, A-X2

X and root output source

x.y

None

True

A1, A-X1, A-X2

X and root output source

x.y.z

A-XYZ1

True

A1, A-X1, A-X2, A-XYZ1

x.y.z, x and root output source

Security

A-SEC

False

A-SEC

Since the additional identifier is set to FALSE, no output source aggregation

Security.access

None

True

A-SEC

Since the additional identifier is set to FALSE, there is only a secure output source.

Often, users not only want to customize their destinations, but also include customization of output formats. This is to reach the destination by setting a layout (layout) to the output source.

For example, the PatternLayout layout with "% R [% T]% -5P% C-% M% N" conversion format is similar to the content below.

176 [main] info org.foo.bar - Located Nearest Gas Station.

The first field is the time that the program starts to the current expense. The second field is a thread that issues a log request. The third field is the level of the log statement. The fourth is the name of the log recorder associated with the log request. The content behind the "-" symbol is the message of the log statement.

As is important, log4j will be based on the standard modification (render, such translation, not known whether it is appropriate). For example, if you often need to record ORANGES, this is an object category that is used in your current project. You can register an ORANGEREREREER class. When an ORANG needs to record the log, the orangerenderer class object will be called. Class level. For example, assuming Oranges is a fruit, if you register a Fruitrenderer class, including all Oranges fruit will be modified by the FruitRenderer class unless you specify an ORANGERERERER.

Renderer objects must implement ObjectRenderer interface

Configure

Log Requests that insert application code require considerable preparation and effort. Observation shows that about 4% of the code is used to output a log. As a result, even if a moderate size application has thousands of log statements being embedded in the code. Given their numbers, manage these statements into urgent things, without having to modify manual.

The log4j environment is a fully parameterized configuration. However, configuring log4j with profiles is very flexible. Currently, profiles can use XML or Java property files (key values) format

However, try to configure a fictional application myApp with log4j.

Import com.foo.bar;

// Import log4j classes. Import org.apache.log4j.logger;

Import org.apache.log4j.basicconfigurator;

Public class myapp {

// Define a static logger variable so thing it references the // logger instance named "myapp". Static logger logger = logger.getlogger (myapp.class);

Public static void main (String [] args) {

// SET UP A Simple Configuration That Logs on The Console. Basicconfigurator.configure ();

Logger.info ("Entering Application."); bar bar = new bar (); bar.doot (); logger.info ("exiting application.");}}

MyApp starts from the import-related class. It then defines a static log recorder variable using MyApp, this MyApp happens to be a complete class name.

MyApp uses BAR classes defined in com.foo packages

Package com.foo; import org.apache.log4j.logger;

Public class bar {static logger logger = logger.getlogger (bar.class);

Public void DOIT () {logger.debug ("DID IT Again!");}}

The call to the BasicConfigurator.configure method creates a relatively simple log4j setting. This method is the consolerapnder output source of the hard wiring (hardwired) to the root log recorder. The output will be formatted using a layout patternLayout, and the layout PatternLayout is set to "% -4R [% T]% -5p% C% X-% M% N" format.

Note the default value, the root log logger is set to the level.debug level. MyApp's output is:

INFO MyApp - Entering Application.

36 [main] debug com.foo.bar - DID IT Again!

INFO MYAPP - EXITING Application.

Below this figure depicts the object map of MyApp after calling the BasicConfigurator.configure party

As a side point of attention, I want to mention that subclasses in log4j are only connected to their existing ancestors. In particular, log recorders named com.foo.bar are directly connected to the root log recorder, thus surrounding unused COM or COM.FOO logs. This significantly improves performance and reduces the log4J-memory consumption (Footprint)

The MyApp class configures log4j by calling the BasicConfigurator.configure method. Other classes only need to import org.apache.log4j.logger, retrieve the log recorder they want, and record in distant.

The previous example always outputs the same log information. Fortunately, it is easy to modify myApp so that you can control the log output in operation. Below is a slightly modified version

Import com.foo.bar;

Import org.apache.log4j.logger; import org.apache.log4j.propertyConfigurator;

Public class myapp {

Static logger logger = logger.getlogger (myapp.class.getname ());

Public static void main (String [] args) {

// BasicConfigurator Replaced with PropertyConfigurator. PropertyConfigurator.configure (args [0]);

Logger.info ("Entering Application."); bar bar = new bar (); bar.doot (); logger.info ("exiting application.");}}

This version of MyApp constructs the PropertyConfigurator class to resolve a configuration file, so create a log

Below is an instance of a configuration file, this configuration file causes the output and the output of the BasicConfigurator class based on this instance.

# Set root logger level to debug and its only appender to a1.log4j.rootlogger = debug, a1

# A1 is set to be a consoleappender.log4j.appender.a1 = org.apache.log4j.consoleappender

# A1 uss patternLayout.log4j.Appender.a1.Layout = org.apache.log4j.patternLayoutLog4j.Appender.a1.Layout.conversionPattern =% - 4R [% T]% -5p% C% X-% M% N

Assume that we no longer be interested in the output of any components in the com.foo package. The following profile shows a possible method, using this method to complete this task.

log4j.rootLogger = DEBUG, A1log4j.appender.A1 = org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout = org.apache.log4j.PatternLayout # Print the date in ISO 8601 formatlog4j.appender.A1.layout.ConversionPattern = % D [% T]%-5P% C -% M% N

# Print Only Messages of Level Warn OR Above In The package com.foo.log4j.logger.com.foo = WARN

The output of myApp configured with this file is as follows.

2000-09-07 14: 07: 41, 508 [main] info myapp - entering application.

2000-09-07 14: 07: 41, 529 [main] info myapp - exiting applations.

Since the log recorder com.foo.bar does not have a given level, it inherits its level from com.foo, in the configuration file, COM.foo is set to WARN. The log statement of the bar.doit method has a debug level, which is lower than the level of WARN at the logger. Therefore, the log request of the DOIT () method is prohibited.

Here is a configuration file with multiple output sources.

Log4j.rootlogger = Debug, Stdout, R

Log4j.appender.stdout = org.apache.log4j.consoleappenderlog4j.Appender.stdout.Layout = org.apache.log4j.patternlayout

# Pattern to output the caller's file name and line number.log4j.Appender.stdout.Layout.conversionPattern =% 5P [% t] (% F:% L) -% M% N

Log4j.Appender.r = org.apache.log4j.rollingfileappenderlog4j.Appender.r.file = example.log

Log4j.Appender.r.maxfilesize = 100kb # Keep One Backup filelog4j.Appender.r.maxbackupindex = 1

Log4j.Appender.r.Layout = org.apache.log4j.patternLayoutLog4j.Appender.r.Layout.conversionPattern =% P% T% C -% M% N

Use this profile call Enhanced myApp will output the following on the console.

INFO [MAIN] (myapp2.java: 12) - Entering Application.

Debug [main] (bar.java: 8) - doing it again!

Info [main] (myapp2.java:15) - exitation application.

In addition, as the root logger has been allocated a second appender, output will also be directed to the example.log file. This file will be rolled over when it reaches 100KB. When roll-over occurs, the old version of example.log IS automatically moving to example.log.1.

In addition, since the root log recorder is assigned to the second output source, the output will be directed to an example.log file. When this file is 100KB, it will flip (Rolled over) files, when flip occurs, the old version of Example.log will be automatically moved to the eXample.log.1 file, for obtaining these different log behaviors, We don't have to compile the code. We can record the UNIX Syslog process, redirect all of the output to a NT event logger, or orient to log events to a remote log4j server, which can record logs in accordance with a local server rule, for example, can pass orien A log event to the second Log4j server.

Default initialization process

The Log4J class library does not have any assumptions to its environment. In particular, the log4j does not have a default output source. However, in some definition, the statically initializer of the log recorder will try to automatically configure log4j. The Java language guarantees that the class's static initializer can only be called once when loading classes in the memory. Different types of loaders may load different copies of the same class, remember this is important. The Java virtual machine believes that the copy of these same classes is completely unrelated.

The default initialization is very useful in the correct entrance to the application of the operating environment. For example, under the control of the web-server, the same application can be treated as a separate application, applet, or servlet.

The following definition is the exact default gaze algorithm:

1. Set the log4j.defaultInito override system properties for any other value, "false" will cause the log4j to ignore the default initialization process (this process).

2. Set the resource string variable to the system attribute value of log4j.configuration. The best way to specify the default initialization file is through the system properties of log4j.configuration. In the event that the system properties log4j.configuration is not defined, you can set string variable resources to its default value "log4j.properties".

3. Try to convert resource variables as URL

4. If the resource variable cannot be converted to the URL, for example, the resources are found in the classpath by calling the return value URL or the returning value URL. Note that the string "log4j.properties" contains an ugly URL.

Refer to the Loader.GetResource (Java.lang.String) method, get a list of findings.

5. If there is no URL, the default initialization is ignored. Others, to configure log4j by URL.

Often use the PropertyConfigurator class to parse the URL to configure log4j, if the URL ends with the ".xml" suffix, will use Domconfigurator to explain. You can have the selection to specify a custom configurer. The system attribute value of log4j.configuratorclass is used as the full class of your custom configurer. The custom configurator you specify must implement the Configurator interface.

Configuration instance

Default configuration under Tomcat

In a web server environment, Log4j's default initialization is particularly useful. Under Tomcat 3.x and 4.x, you should place log4j.properties in the web-inf / class directory of your web application. Log4 will discover this attribute file and initialize it yourself. This is very easy to do.

Before Tomcat is started, you can also choose to set the system properties log4j.configuration. Tomcat 3.x Environment Variable Tomcat_OPTS is used to set the command line option. Tomcat 4.0 Sets the Catalina_OPTS environment variable instead Tomcat_opts. Example 1

UNIX shell command

Output tomcat_opts = "- dlog4j.configuration = foobar.txt" tells the log4j to use file foobar.txt as the default configuration file. This file should be placed in the directory of your application web-inf / class. Each web application will use a different default configuration file because each file is with relative web applications.

Example 2

UNIX shell command

Output tomcat_opts = "- DLOG4J.DEBUG4J.CONFIGURATION = FOOBAR.XML" tells the log4j to output the internal debugging information of log4j, and use file foobar.xml as the default configuration file. This file should be placed in the directory of your application web-inf / class. Since the file is ended with the .xml suffix, it will use Domconfigurator to read the file. Each web application will use a different default configuration file because each file is with relative web applications.

Example 3

Windows shell command

Set Tomcat_OPTS = -dlog4j.configuration = foobar.lcf -dlog4j.configuratorclass = com.foo.barconfigurator tells the log4j to use file foobar.lcf as the default configuration file. Due to the definition of the log4j.configuratorclass, the file will be read with the COM.FOO.BARCONFIGURATOR defined. Each web application will use a different default configuration file because each file is with relative web applications.

Example 4

Windows shell command

Set Tomcat_OPTS = -dlog4j.configuration = file: / c: /foobar.lcf tells the log4j to use the file c: /foobar.lcf as the default configuration file. The configuration file is completely specified by using the URL file: / c: /foobar.lcf. So all applications use the same configuration file.

Different web applications will load the log4j class through their respective class loadingers (ClassLoaderss). Therefore, each image of the log4j environment is independent and does not require any mutual synchronization. For example, FileAppenders defines the same method in multiple web application configurations, which will all write the same file. This result is likely to be unsatisfactory. You must ensure that the log4j configuration of different web applications does not have to be the same potential system resource.

Initialization servlet

It is also possible to use a special servlet weekly log4j. Below is an example

Package com.foo;

import org.apache.log4j.PropertyConfigurator; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.IOException;

Public class log4jinit extends httpservlet {

Public void init () {string prefix = getServletContext (). getRealPath ("/"); string file = getInitParameter ("log4j-init-file"); // if the log4j-init-file is not set, Then no point IN trying if (file! = null) {propertyconfigurator.configure (prefix file);}} public void doget (httpservletRequest Req, httpservletResponse res) {}}

Define the following servlet in the web.xml file of your web application

Log4j-init

com.foo.log4jinit

LOG4J-INIT-FILE

WEB-INF / CLASSES / LOG4J.LCF

1

Write an initialized servlet is the most flexible method for initializing log4j

Nested diagnostic environment

Most real world systems must handle multiple clients concurrently. In such a typical multi-threaded system, different threads will process different clients. The logging log is especially suitable for tracking and commissioning complex distributed applications. A simple way to distinguish the log output from another client is to install a logger to each client. This will result in an increase in the logger and increase the maintenance of the entire log.

A simple technology is that there is a unique timestamp for each of the same client. This method is described in Pattern Languages ​​of Program Design 3 (Edited by R. Martin, D. Riehle, And F. Buschmann (AdDison-Wesley, 1997)) in the PatternalNs for Logging Diagnostic Messages.

Each request has a unique timestamp, the user presses the environment information into NDC, NDC is the abbreviation of NESTED DIAGNOSTIC CONTEXT. The NDC class is as follows.

PUBLIC CLASS NDC {

// used when printing the diagnostic

Public static string get ();

// Remove the top of the context from the ndc.

Public stat String pop ();

// Add diagnostic context for the current thread.

Public Static Void Push (String Message);

// Remove The Diagnostic Context for this Thread.

Public static void remove ();

}

Each thread manages NDC as a environmental information stack. Note that all methods of org.apache.log4j.ndc classes are static. Assuming that NDC print is proven, each time a log request is processed, in log output information, the appropriate log4j component will contain the full NDC stack of the current thread. This is completed without user feeling. This user is responsible for using the PUSH and POP methods by using some of the definition points in the code, and the correct information is placed in the NDC.

To illustrate this, let us give an example, this example is the servlet distribution content to many clients. Before performing other code, the servlet can compile NDC at the beginning of the request. Environmental information may be the name of the client host and the requested internal information, typically information containing cookies. Therefore, even if the sevlet is serving multiple clients at the same time, the log will start recording through the same code, that is, even at the same log recorder, the log is still a different NDC stack, the log is still It can be distinguished. However, some robust applications, such as virtual host web servers, must record different information according to software components in different virtual host environments and software components. Recently Log4j released version begins to support multi-level trees. This improvement allows each virtual host to have its own copy of your own log recorder level

performance

The reply logging that is often mentioned is calculated. This is a reasonable concern, even if an appropriate size application may also produce thousands of log requests. A large number of work is spent on adjusting and improving the performance of the log. Log4j advocates fast and flexible: speed first, flexibility second.

The User Should Be Aware of The Following Performance Issues.

Users should pay attention to the performance issues below

1. When the log performance is turned off when the log is turned off.

When the log is completely turned off, or it is set to a level, the consumption of the log request includes a method call and a integer comparison. On the 5 to 50 nanoseconds ranges on the machine at 233 MHz Pentium II.

Then, the method calls "invisible" consumption of the parameter structure.

For example, some log recorders, as follows,

Logger.debug ("Entry Number:" i "IS" String.Valueof (entry [i]));

The constructive message parameter causes consumption, that is, the conversion integer I and array entry [i] is a string, and there is a connection media string, regardless of the message is recorded. This parameter conversion may be very high and depend on the size of the conversion parameters.

Avoid constructing parameters consumption:

IF (logger.Indebugenabled () {

Logger.debug ("Entry Number:" i "IS" String.Valueof (entry [i]));

}

This will not result in consumption of constructor, if the debugger is not available. On the other hand, if the logger is being debugged, it will result in two calculation consumption regardless of whether the log logger is available. This is an insignificant fee (Overhead) because the Evaluating) A log recorder consumption is about 1% of the logger really consumes.

In log4j, log requests are processed by log recorder instances. The logger is a class rather than an interface. This significantly reduces the consumption of method calls, of course, this is the cost of flexibility (this Measurably Reduces the cost flexibility).

Some users use pretreatment or real-time compilation technology to compile all log statements. This will guide excellent performance efficiency without affecting logging. However, since the application binary does not include any log statement, logging cannot becomes a binary (Logging cannot be turned on for tria binary). My point of view, this is an unprically proportional price, in order to achieve small performance.

2. When the log record starts, decide whether the performance of the log is logged.

Properties across the logger hierarchy are potential. When logging starts, log4j will need to compare the level of log request and log request processor. However, the logging can not have the specified level; they can inherit the level from the logger hierarchy. therefore. Before inheriting a level, the logger may need to search for its ancestors. It has already spent a lot of effort to make it as fast as possible across this level. For example, the sub-log recorder is only connected to the ancestors they exist. In the previously displayed BasicConfigurator instance, the log recorder named com.foo.bar is directly connected to the root log recorder, so avoiding the COM and COM.FOO do not exist. This significantly increases the speed of spanning, especially in the "sparse" hierarchy

Typical consumption across the hierarchy is 3 times when it is completely closed than logging.

3. Virtually output information

This is the formatted log output and the consumption of it to the target. Here, a large number of efforts are once again taken to make the layout (formatting device) as fast as possible. This is the same as the output source. Typical consumption of logs that truly logging is about 100 to 300 microseconds. Refer to org.apache.log4.performance.logging Get exact numbers.

Although log4j has a lot of features, its primary goal is speed. In order to improve performance, some log4j components have been overridden many times. However, contributors are still constantly proposing newly optimization. You should be very happy, when you know when using the SimpleLayout configuration log log, the test shows the speed of log4j and system.out.println.

in conclusion

Log4j is an excellent log package written in Java. It is one of its distinct features that inheritance log recorder concept. Use the logger hierarchy to make it possible to output any particle size control log statement. This helps reduce log output and minimize log consumption.

One of the features of the log4j API is its easy management. Once the log statement is inserted into the code, they can control it with a configuration file. They can have the activation or not activated. The log4j package is designed to be saved in the logfi code without causing a lot of performance consumption.

thank

Thank you very much N. Asokan reviewed this article. One of his founders of his logger concept. Thank Nelson MINAR to encourage me to write this article. He also made a lot of useful suggestions and amendments to this article. Log4j is the result of collective efforts. Thank you all author who contributes to this project. There is no exception, the best features in the package have been widely created in the user community.

转载请注明原文地址:https://www.9cbs.com/read-14632.html

New Post(0)