Log4j Concise Manual

xiaoxiao2021-03-06  87

Log4j Concise Manual

1 Overview

This article mainly describes the unique characteristics of the LOG4J API and its design principle. Log4j is a project based on many authors. It allows the developer to control the output of the log in any interval. It achieves flexible settings at runtime by setting a configuration file outside. Most importantly, log4j has a smooth learning curve. Note: Depending on the feedback from the user, it is easy to add addiction.

2. Introduction

Almost all large applications include its own logs and tracking APIs. Adapt to this rule, E.U. Semper project determines writing its own tracking PAI. This is early 1996. After countless times, after several deformations and many work, the API has become a popular Java log package today. This package is published in Apache Software License protocol, a mature open source. The latest log4j version, including all source code, Class files, and documents, you can find it at http://jakarta.apache.org/log4j/. Incidentally, log4j has provided an interface to C, C , C #, Python, Ruby, and Eiffel language.

In order to debug, the insertion log output is a method of low-tech ingredients, but it may be a unique method because the debugger is not always available or can be adapted, especially for multi-threaded distributions .

Experience stated that debugging is an important part of the software development cycle.

Log4j has several advantages:

l First, it provides an accurate environment for running procedures. Once the code is inserted, debugging information can be generated without manual intervention.

l Second, the log output can be preserved in the permanent media in a permanent media.

In addition, in addition to the development cycle, a full detailed log package can be used as a subsequent statistical tool.

Log4j is of course its shortcomings, it may slow down the program. If it is too detailed, it may cause the screen blindly scrolling. These situations are excluded, and log4j is reliable, fast, can be expandable. Because the logs are rarely the main purpose of an application, designers are working hard to make log4j API learning and use simplification.

3. Log class, output source and layout

Log4j has three main components: log category, an output source (Appenders), and layout. These three types of components work together such that the developer can record them according to the type and level of the information, and control the output format and location of this information at runtime.

3.1 Log class hierarchy (Loggers)

The LOG4J's primary relative to the simple use of the system.out.println () method is based on its ability to do other information output while prohibiting some specific information outputs. This capability is derived from log namespace, that is, all log declarations, it is classified according to the formulas selected by some developers. Previous observation guides us to choose categories as the center concept of the package. However, since the LOG4J version 1.2, the Logger class is replaced by the Catalog class. For those who are familiar with Log4j, the Logger class can be imagined to be just a category class alias.

Loggers is designated as entities, and the name of the logger is sensitive, they follow the following naming rules:

Naming inheritance

If the name of the category (after adding a point) is the prefix of its subcategory name, it is another ancestor of another category.

If there is no other inheritance relationship between a category (Logger) and its subcategory, we call the relationship between PARENT and Child.

For example, category "com.foo" is a Parent, COM.FOO.BAR. Similarly, "java" is "java.util" Parent, is the father of "java.util.Vector". This naming rule should be familiar with most developers. The root category is located at the top of the Logger inherited structure. There are two exceptions:

It has always existed

2. It cannot be obtained according to the name.

The static method of calling classes logger.getrootlogger can get it. All other Loggers can get their own instances by static methods logger.getlogger. This method takes the hope of the Logger name as a parameter. Some basic methods of logger are as follows:

Package org.apache.log4j;

PUBLIC logger class {

// Creation & RetrievalMETHODS:

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);

// generic printing method:

Public void log (level L, Object Message);

}

Loggers can be assigned levels. All levels of levels include:

l Debug

L info

l Warn

l error

l Fatal

They are defined in org.apache.log4j.level class. Although we don't encourage, you can define your own level by inheriting the Level class. We will then introduce a better way.

If a logger is not assigned a level, it will inherit from an allocated ANCESTOR that is allocated level.

Level inheritance

For a given Logger C, its inheritance level is equal to the first level of the Logger that has a non-air-class Logger from the start.

To ensure that all Loggers can eventually be inherited to a level, root Logger usually has a level that has been defined.

The data in the following four tables demonstrate the results obtained according to the above rules.

Category name

Allocation level

Inherited level

Root ProT Proot X None Proot X.Y None Proot x.y.z None Proot

EXAMPLE 1

In Example 1, only root Logger defines a level, its level value - "proot" is inherited by all other Loggers X, X.Y, and X.y.z.

Category name

Allocation level

Inherited level

Root ProT ProT X PX PX X.Y PXY PXY X.Y.Z PXYZ PXYZ

EXAMPLE 2

In Example 2, all Loggers have a assigned level value, so they don't need levels.

Category name

Allocation level

Inherited level

Root ProT ProT x PX PX X.Y None PX X.Y.Z PXYZ PXYZ

EXAMPLE 3

In Example 3, root logger, and x and x.y.z were assigned a level proot, PX, and PXYZ. Logger x.y inherits the level value PX from its Parent X.

Category name

Allocation level

Inherited level

Root ProT ProT X PX PX X.Y None PX X.Y.Z None PXexample 4

In Example 4, roots Logger and X are assigned a level "preoke" and "PX", Logger X.Y and X.y.z, are inherited from allocated levels of Ancestor x allocated.

We need to implement a log request by calling one of the example methods of the logger. These output methods are Debug, Info, Warn, Error, Fatal, and Log.

Distance the level of the request of the log by defining the output method. For example, if c is an instance of a Logger, then declares that C.info is an INFO level log request.

If the level of the request of a log is higher than or equal to the level of the log, it can be enabled. Conversely, it will be disabled. A Logger that is not arranged will be inherited from its parents. This rule summarizes the following.

Basic selection rules

If a log request of a level P is occurred in a logger of Q, if P> = Q, the request will be enabled.

This is the core principle of log4j. It assumes that level is in an orderly. For standard levels, we define Debug

The following is an example of this rule.

// 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 progamitcally. this is usually done

// in Configuration FILES.

Cat.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

Logger.debug ("Starting Search for NEAREST GAS Station);

// The logger instance barlogger, named "com.foo.bar",

// Will inherit its level from the logger named

// "com.foo" thus, The Following Request is enabled

// Because info> = info.

Barlogger.info ("Located Nearest Gas Station);

// this request is disabled, Because Debug

Barlogger.debug ("EXITING GAS STATION SECH");

Calling the getLogger method will return an instance of a logger object of the same name.

E.g,

Categoty x = logger.getlogger ("wombat");

Categoty y = logger.getlogger ("wombat");

X and Y reference are the same logger object.

This way we can define a Logger first, then you can reach an instance of the Logger we have defined in other parts of the code. With the basic biological theory - the opposite of the child, Log4j's loggers can Create and configure in any order. In particular, a sub-Logger that is later instantiated "Parent" Logger can find and connect to it.

Configuring the log4j environment is usually performed when an application is initialized, and the best way is to read a configuration file.

This method we will introduce it.

Log4j makes it easy to name Logger through software components. We can define a logger in each class with a static initialization method of Logger, so that the name of the Logger is equal to the global name of the class name, and the logger is named. This is an effective simple definition of a Logger method. Because the log output has the name of the class that generates the log, this naming policy makes us easier to locate the source of a log information. Although ordinary, it is one of the common strategies of naming Logger. Log4j does not limit the possibility of defining the Logger. Developers can definite the name of the Logger in accordance with their wishes.

However, named Logger is the best way to be currently known as the location of the class.

3.2 Output source (Appenders) and layout (Layouts)

Selected or disable log request is only part of the log4j. The log4j allows the log request to be output to multiple output sources. With log4j, an output source is called a appender. Appender includes Console (Console), Files (Files), Remote Socket Servers, JMS (Java Information Services), NT Event Loggers, And Remote Unix Syslog Daemons (Background Log Service for Remote Unix). It can also be asynchronous records.

A Logger can set more than one appender.

Add an APPENDER to a given Logger with the AddAppender method. For a given logger, each of its effective log requests are forwarded to the Logger all Appender on the appender of the Logger's Logger. In other words, appender automatically enables inheritance from its parent. For example, if a root Logger has a Console Appender, then all valid log requests will be at least on the Console. If a Logger called C has an Appender of a file type, it will take effect on itself and all its sub-loggers. We can also overload the default behavior of the appender by setting the Appender's Additive Flag to False, so that the attributes of the inheritance are not taken effect.

The rules for adjusting the output source (appender) are as follows.

Adder Additive (appender additivity)

A log-defined output of a logger named C will continue to its own and its ANCESTOR Logger's appenders. This is the meaning of the term "appender additivity".

However, a Annestor Logger P of Logger C, which is set to false, then C's output will be positioned to all the Appender of all C, and all Appender from it from it to P.

The attached tag (Additive Flag) is default to True. The following table is an example.

Loggername

AddedAppenders

AdditiveFlag

Output Targets

Comment

Root A1 Not Applicable A1 The Root Logger IS Anonymous But Can Be Accessed with The Logger.getlogger () Method. There Is No Default Appender Attached To Root. X A-X1, A-X2 True A1, A-X1, A-X2 Appenders of "x" and root. XY None True A1, A-X1, A-X2 appenders of "x" and root. XYZ A-XYZ1 TRUE A1, A-X1, A-X2, A-XYZ1 Appenders in "XYZ "," X "and root security a-secret," ,,,,,,,,,,,,,,,,,

Security.access None True A-Sec The Appenders of "Security" Because The Additivity Flag in "Security" is set to false.

Often, users want to customize but not only output, but also define the output format. This is done by adding a Layout on an Apnder. Layout is responsible for formatting a log request based on the hopes of the user. Appender is the destination responsible for sending formatting to its destination. PatternLayout, as part of the Log4J standard version, let the user refer to the format of the log in the format of the PrintF method similar to the C language.

For example, PATTERNLAYout of the conversion mode is "% R [% T]%-5p% C -% N" will output the following information:

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

The first field is the number of milliseconds that have fallen after the program begins.

The second field is a thread that makes a log.

The third field is the level of log.

The fourth field is the name of the logger related to the log request. The text after "-" is an expression of information.

Log4j will modify the content of log information according to user-defined formulas. For example, if you often need to record ORANGES, an object type that is used in your current project, then you can register an ORANGERERERER, which will be called when an Orange needs to be recorded.

Object renders a similar structure inheritance. For example, assuming ORANGES is Fruits if you register a FruitRenderer, all fruits include ORANGES will be rendered by FruitRenderer. Unless you register an Orange.

Object rendering must implement ObjectRenderer interface.

4. Configuration

Insert log requests to the application's code requires a lot of pre-planning and final efforts. Observation shows that about 4% of the code is used to output.

Therefore, the size of the size mode is embedded with thousands of log output statements. In order to manage the output status of these logs in a manual manner, it is imperative to output to the log output to numbered and specification.

Log4j has sufficient configurability in the program. However, configuring log4j with a configuration file with greater flexibility. Currently, its profile supports both formats of XML and Java Properties files.

Let us demonstrate how it is doing in an example. Assume that there is a program myApp with log4j.

Import com.foo.bar;

// Import log4j class.

Import org.apache.log4j.logger;

Import org.apache.log4j.basicconfigurator;

Public class myapp {

// define a static logger variable so that 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 begins with the relevant class of log4j, then it defines a static Logger variable and gives a full path name of the "MyApp" class.

MyApp uses class BARs defined in package com.foo.

Package com.foo;

Import org.apache.log4j.logger;

Public class bar {

Static logger logger = logger.getlogger (bar.class);

Public void Doot () {

Logger.debug ("DID IT AGAIN!");

}

}

Call the BasicConfigurator.configure () method created a fairly simple Log4j setting. It joins one

CONSOLEAPPENDER to root Logger. The output will be formatted by PatternLayout in "% -4R [% T]% -5p% C% X-% M% N" mode.

Note that the root Logger is assigned the level of Level.Debug by default.

MyApp's output is:

INFO MyApp - Entering Application.

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

INFO MYAPP - EXITING Application.

Subsequent graphics describe the object map of MyApp after calling the BasicConfigurator.configure () method.

While wanting to remind, Log4j's child logger is only connected to their parents already existing. In particular, logger named com.foo.bar is directly connected to the root Logger instead of the useless COM or com.foologigger. This significantly improves program performance and reduces memory occupation.

MyApp class configuration log4j is by calling the BasicConfigurator.configure method. Other classes only need to introduce org.apache.log4j.logger classes, find the Logger they want to use, and use it to play.

Previous examples typically output the same log information. Fortunately, modify myApp is easy to log losing

You can be controlled at runtime. Here is a small 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.");

}

}

The modified MyApp Notification Program calls the PropertyConfigurator () method to resolve a configuration file and set the log according to this profile.

Here is an example of a configuration file, which will produce the same output result as the basic example of BasicConfigurator.

# Set root logger level to debug and its Only Appender to A1.

Log4j.rootlogger = Debug, A1

# A1 is set to be a consoleapplender.

Log4j.Appender.a1 = org.apache.log4j.consoleAppender

# A1 Uses patternLayout.

Log4j.Appender.a1.Layout = Org.apache.log4j.patternlayout

Log4j.Appender.a1.Layout.conversionPattern =% - 4R [% T]% -5p% C% x -% M% N

Suppose we are not interested in any class of any classes of the com.foo package, subsequent configuration files show us one of the methods of implementing this purpose.

Log4j.rootlogger = Debug, A1

Log4j.Appender.a1 = org.apache.log4j.consoleAppender

Log4j.Appender.a1.Layout = Org.apache.log4j.patternlayout

# Print The date in ISO 8601 FORMAT

Log4j.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 MYAPP that is configured with this profile will be output 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.

When logger com.foo.bar is not assigned a level, it will inherit from com.foo, which is set at the WARN level in the configuration file. Log defined in bar.doit method is a debug level, lower than WARN, so the log request for the DOIT () method is disabled.

Here is another profile, which uses multiple appenders.

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.rollingfileappender

Log4j.Appender.r.file = example.log

Log4j.Appender.r.maxfilesize = 100kb

# Keep One Backup File

Log4j.Appender.r.maxbackupindex = 1

Log4j.Appender.r.Layout = org.apache.log4j.patternlayout

Log4j.Appender.r.Layout.conversionPattern =% P% T% C -% M% N

The following information will be output as this configuration file call.

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

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

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

In addition, since the root Logger has the assigned second Appender, the output will also be oriented to the example.log file. This file is automatically backed up when the file size is 100KB. When backed up, the old version of the eXample.log file is automatically moved to file eXample.log.1.

Note We don't need to recompile the code to get these different log behaviors. We can easily enable the log to output to UNIX Syslog Daemon, redirect all COM.FOO to NT Event Logger, or forward the log to a remote Log4J server, which is logged according to the local Server policy. For example, forward log events to the second Log4j server.

5. Default initialization process

The log4j library does not make any assumptions to its environment. Especially there is no default log4j appender. In some particularly a well-defined environment, Logger's static inIalizer will try to automatically configure log4j.

The Java language features ensure that only the static initializer of the class is only called once when it is loaded to memory. It is important to remember that different types of loaders may load a completely different copy of the same class. These same copies are considered completely unsatisfactory by virtual machines.

The default initialization is very useful, especially in the case where the operating environment relied on some applications is accurately positioned. For example, the same application can be used as a standard application, or an applet, or a servlet under Web-Server.

Accurate default Initialization principle is defined as follows:

1. Set the system properties log4j.defaultinitoverride is other than other values ​​other than "false", then log4j will skip the default Initialization process.

2. Set the resource variable string to the system properties log4j.configuration. The best way to define the default initialization file is through system properties log4j.configuration. In the event of a system property log4j.configuration is not defined, then set the string variable resource to its default value log4j.properties.

3. Try to convert the resource variable as a URL. 4. If the value of the variable resource cannot be converted to a URL, for example due to the Malformedurlexception violation, then search for Resource from the classpath by calling org.apache.log4j.helpers.Loader.GetResource (resource, logger.class) method, it will return A URL and notify "log4j.properties" value is an error URL. Look at see loader.getResource (java.lang.string) View the list of search locations.

5. If there is no URL being discovered, then give up the default Initialization. Otherwise, use the URL to configure log4j.

PropertyConfigurator will be used to parse the URL, configure log4j, unless the URL ends with ".xml". In this case DOMCONFIGURAM will be called. You can have a chance to define a custom Configurator. System Properties Log4j.configuratorclass's value takes the full path to your custom class name. Your custom Configurator must implement the Configurator interface.

6. Configuration example

6.1 Initialization under Tomcat

The default Log4j initialization typical application is in a web-server environment. Under Tomcat3.x and Tomcat4.x, you should put the configuration file log4j.properties in your web-INF / CLASSES directory of your Web application. Log4j will discover attribute files and initialized this. This is the easiest way to make it work.

You can also choose to set the system properties log4j.configuration before running Tomcat. For Tomcat 3.x, Tomcat_OPTS system variable is an option to set the command line. For Tomcat 4.0, use the system environment variable Catalina_OPTS instead of Tomcat_OPTS.

EXAMPLE 1

UNIX command line

Export Tomcat_opts = "- DLOG4J.CONFIGURATION = FOOBAR.TXT"

Tell the log4j as the default configuration file with file foobar.txt. This file should be placed in a web-inf / class directory. This file will be read by PropertyConfigurator. Each Web-Application will use different default configuration files because each file is related to its web-application.

EXAMPLE 2

UNIX command line

Export Tomcat_opts = "- DLOG4J.DEBUG -DLOG4J.CONFIGURATION = FOOBAR.XML"

Tell the log4j output log4j-internal debugging information and use FOOBAR.XML as the default configuration file. This file should be placed in your web-application's web-inf / class directory. Because there is a .xml extension, it will be read by Domconfigurator. Each Web-Application will use different default configuration files. Because each file is related to its web-applation.

EXAMPLE 3

UNIX command line

Set tomcat_opts = -dlog4j.configuration = foobar.lcf -dlog4j.configuratorclass = com.foo.barconfigurator

Tell the log4j to use the file foobar.lcf as the default configuration file. This file should be placed in your web-application's web-inf / class directory. Because the log4j.configuratorclass system properties are defined, the file will be parsed by a custom COM.FOO.BARCONFIGURATOR class. Each Web-Application will use different default configuration files. Because each file is related to its web-applation. EXAMPLE 4

UNIX command line

Set tomcat_opts = -dlog4j.configuration = file: / c: /foobar.lcf

Tell the log4j to use the file foobar.lcf as the default configuration file. This configuration file defines a full path name with URL File: / C: /foobar.lcf. The same configuration file will be used by all Web-Application. Different Web-Application will load LOG4J through their own type loaders. In this way, each Log4J environment will operate independently without any mutual synchronization. For example: FileAppenders that exactly the same output source will try to write the same file in multiple web-applications. The result is like lack of security.

You must ensure that the Log4j configuration of each different web-application is not used to use the same system resource.

6.2 initialization of servlet

It is also possible to use a special servlet to do LOG4J initialization. As 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, the no point in trys

IF (file! = NULL) {

PropertyConfigurator.configure (prefix file);

}

}

Public void doget (httpservletRequest Req, httpservletResponse res) {

}

}

Define subsequent servlets in Web.xml for your web-application.

Log4j-init

com.foo.log4jinit

log4j-init-file

Web-inf / class / log4j.lcf

1

Write an initialized servlet is the most elastic initialization Log4j method. There is no restriction in the code, you can define it in the servlet's init method.

7. NESTED DIAGNOSTIC CONTEXTS

Systems in the real world often have to deal with multiple client requests. In such a typical multi-threaded system, different threads will process different clients. Logging is particularly adaptable to debugging and tracking of this complex distributed application. A common way to distinguish the logging of each client is to instant a new independent Logger for each client. This leads to a large number of Logger, and the cost of management has also exceeded the logging itself.

Uniquely identifying each log request is a lightweight technology. Neil Harrison describes this method in Pattern Languages ​​of Program Design 3, Edited by R. Martin, D. Riehle, And F. Buschmann (Addison-Wesley, 1997).

In order to uniquely identify each request, the user pushes context information into NDC (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 ();

}

NDC is like a stack to manage each thread. Note that all the org.apache.log4j.ndc classes are static. Suppose the NDC output is turned on, and each time a log request is generated, the appropriate log4j component contains a complete NDC stack for the thread that will output log. This is done without user intervention, users are only responsible for positioning the correct information in NDC, inserting small PUSH and POP methods in the correct location in the code. Conversely, there is a great change in the PER-Client implementation method in the code.

In order to demonstrate this, let's take a sedate to an anonymous client as an example. This servlet can establish NDC when starting initialization before each other code. Context information can be the name of the client host and other information in the request.

Typical information includes cookies. Therefore, even if servlet provides services to multiple customers, logs are initialized, such as the same logger, can still be distinguished because each customer request will have different NDC stacks. In contrast this with the complexity of passing a freshly instantiated logger to all code exercised during the client's request.

However, some strange procedures, such as web server logging logs of virtual hosts, not generally relying on the context of the virtual host, but also rely on the software component to issue a request. Recently, the release version of the log4j supports multi-layer tree structure. This enhancement allows each virtual host to handle it in its own logger.

8. Optimize

A parameter that is often cited on Logging is a cost of spending. This is a reasonable concept, a moderate application may generate thousands of log requests. Many efforts are spent on measurement and debugging Logging optimization. Log4j requires rapid and elasticity: the speed is most important, and the flexibility is second. Users should pay attention to subsequent optimization suggestions. 1. When the log is disabled, the log is optimized.

When the log is completely closed, a log request is equal to a method of calling plus an integer comparison time. This cost is typically between 5-50 nanoseconds on the 233 MHz Pentium II machine. However, method calls include hidden costs for parameters.

For example, for Logger Cat,

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

It causes the cost of building information parameters, for example, transforming integer I and Entry [i] to a string, and connect the intermediate string, whether or not the information is output. The construction cost of this parameter may be high, it mainly determines the size of the parameters called the call.

The cost of avoiding parameters should be as follows, and if the logger's Debug is turned off, this will not cause the spending of parameters. On the other hand, if the logger is debug, it will generate two tricks that the Logger can use. Once in Debugenable, once is Debug. This is irrelevant, because the ability to judge the log only about 1% of the actual time spent on the log.

In log4j, log requests in the Logger class. Logger is a class instead of an interface. This reduces the elasticity cost of the method call.

Of course, users use pre-processing or compile time technology to compile all log declarations. This will result in perfect implementation results. However, because the binary application does not include any log declarations, the log cannot be turned on the binary. With my point of view, it is not worthwhile to exchange smaller performance optimization in this large cost.

2. When the log status is enabled, the log is optimized.

This is an essentially optimized Logger level. When the log status is open, the log4j still needs the level of the request and the level of Logger. However, Logger may not be arranged at a level; they will inherit from their Father. This way, Logger may need to search for its ancestor before inheriting.

Here is a serious effort to make the level search as possible. For example, the child logger is only connected to its presence of Father Logger.

In the previously displayed BasicConfigurator example, Logger named com.foo.bar is connected to root logger, so it is bypassing the Logger COM and COM.FOO that does not exist. This will significantly improve the speed of execution, especially when parsing the Logger layer structure.

Typical hierarchical resolution is three times that of Logger is completely closed.

3. Optimization of the log information when the log information is output.

This is the formatting of log output and sent it to its output source. Here we have made efforts to make the formatted implementation as fast as possible. Like appender. In fact, typical spending is about 100-300 milliseconds. See org.apache.log4.performance.logging for details.

Although log4j has many features, its first design goal is still speed. Some log4j components have been overridden many times to improve performance. However, contributors often put forward new optimization. You should be satisfied that the execution test with SimpleLayout has shown the output of log4j as fast as System.out.Println.

9. Summary

Log4j is a popular log package written in Java. A distinctive feature is the concept of inheritance in Logger. Inheritance with Logger can be output at any intervals. This reduces the cost of volume and minimization log. Easy management is one of the advantages of the Log4j API. As long as the log definition is added to the code, they can be controlled by the configuration file. They can be selected and sent to different multiple output sources to select a good format.

Log4j's package is designed, and you can keep them in the product without spending a heavy cost price.

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

New Post(0)