Log4j

xiaoxiao2021-03-06  55

Logger

package org.apache.log4j; public class Logger {// create and restore method public static Logger getRootLogger (); public static Logger getLogger (String name); public static Logger getLogger (Class clazz); // print method 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); // common printing method public void log (Level l, Object message }

Structure of the recorder

An instance of a Logger is obtained when using the log4j logger.getlogger () method. If you contain thousands of classes in an app, then you can also need a thousand Logger instances. How to easily configure this thousand Logger instance is a very important issue. Log4j uses a tree inheritance level to solve this problem. Logger is a hierarchical relationship in log4j. It has a common root, located in the uppermost layer, other logger follows the hierarchy of similar packets, such as:

static Logger root = Logger.getRootLogger (); static Logger log1 = Logger.getLogger ( "org"); static Logger log2 = Logger.getLogger ( "org.javaresearch"); static Logger log3 = Logger.getLogger ( "org.javaresearch .log4j.testlog4j ");

In the above code, log1 is the father of log2, is the ancestors of log3, and root is all the ancestors of LOG1, LOG2, LOG3, which are inherited from root. Therefore, in general, only the rootlogger needs to be configured, and other subcrans will inherit the rootlogger configuration. If you modify the configuration of the rootlogger, all other subcunauts also inherit this change. This greatly facilitates the configuration. Now look back at the configuration file in "Quick Start", we only configure the rootlogger, you can control all Logger's behavior.

Level (Level)

A core concept in log4j is that the log level is in an orderly manner. Log4j has built-in 5 log levels:

Debug

The level of the right is higher than the high layout of the left.

Log4j uses the print format of the Printf function in the C language, and the print parameters are shown in Table 1: The message% P output priority specified in% m output code, namely Debug, INFO, WARN, Error, Fatal% R Output Self-Application Start to Output The LOG information consumes the category to which the category belongs is, usually the full name% T output of the class is output to generate the log event.% N outputs a carriage return, the Windows platform is "/ R / n", the Unix platform is "/ N"% D output log time point date or time, the default format is ISO8601, or it can be specified in the format, such as:% D {YYY MMM DD HH: mm: MM: SS, SSS}, Output Similar: October 18, 2002 22: 10: 28,921% l Output Log Event location, including category names, threads that occur, and number of rows in code. Example: Testlog4.main (Testlog4.java: 10) Basic Applications

Log4j configuration

The configuration file is as follows:

#### use two appenders, one to log to console, another to log to a filelog4j.rootcategory = debug, stdout, r

# Print Only Messages of Priority Warn or Higher for Your CategoryLog4j.category.Your.category.name = WARN

#### first appender Writes to consOLELOG4J.APPpender.stdout = org.apache.log4j.consolerappenderlog4j.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

#### Second appender Writes to a filelog4j.appender.r = org.apache.log4j.rollingfileAppenderlog4j.Appender.r.file = example.log

# Control the maximum log file sizelog4j.Appender.r.maxfilesize = 100kb # Archive log file (one backup file here) log4j.Appender.r.maxbackupindex = 1

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

This profile specifies two output sources Stdout and R. The former outputs the log information to the console, and the latter is a rotation log file. The biggest file is 100KB. When a log file reaches the maximum size, log4j will automatically rename Example.log to eXample.log.1, and then rebuild a new Example.log file and rotate sequentially.

Use in web applications

Log4j must complete the initialization before performing other code executions. Because servlet is immediately loaded immediately, in a web application, a special Servlet is usually used to complete the log4j configuration and ensure that this servlet is in other servlets in the Web.xml configuration. Here is an example, as follows: package org.javaresearch.log4j; import java.io *; import javax.servlet *; import org.apache.log4j *; public class Log4JInit extends HttpServlet {public void init () throws... ServletException {string prefix = getServletContext (). GetRealPath ("/"); string file = getServletConfig (). GetInitParameter ("log4j-config-file"); // reads the log4j configuration file IF from the servlet parameter (file! = null) {PropertyConfigurator.configure (prefix file);}} public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {} public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {}}

Log4jinit org.javaresearch. log4j.log4jinit log4j-config-file /properties/log4j.properties 1

Note: The above Load-on-Startup should be set to 1 to load the servlet when the web container is started. Log4j.properties files are placed in the rorties subdirectory of the root or in other directories. It should be stored in the .properties file, so convenient management.

Advanced topic

performance

When recording some log information, it will affect the operating efficiency of the system to a certain extent, and if the log tool is efficient, it is a key. Log4j's primary design goals are efficient, and some key components have renovated many times to continuously improve performance. According to the report of the log4j project team, in the environment of AMD DURON 800MHz JDK1.3.1, log4j judges whether a log statement needs to output only 5 nanoseconds. The actual log statement is also very fast, from 21 microseconds using SimpleLayout (almost as fast as System.out.println), 37 microseconds using TTCCLAYOUT.

Nested diagnostic environment NDC

In a multi-user concurrent environment, different client requests are typically handled by different threads. At this point, you should have different clients in the log information, you can generate a logger for each thread, thus distinguishing which information is part of the information, but this method is not efficient. Log4J has cleverly uses the "NDC (Nest Diagnostic Environment) mechanism proposed by Neil Harrison to solve this problem. Log4j generates a logger for the same category, multiple thread sharing, and it adds information that can distinguish between different threads only in log information. What is NDC? For example, if a servlet receives a concurrent request, create a new thread for each client and assign a NDC stack for saving the request context. This context may be a request for host name, an IP address, or any other information that can be used to identify the request. Thus, since different client processing threads have different NDC stacks, even if this servlet generates multiple thread processing different requests, these log information can still distinguish, as if log4j generates a logger instance for each thread. same. This mechanism is achieved through org.apache.log4j.ndc in log4j. The method of using NDC is also very simple, the steps are as follows: 1. Call ndc.push (string) when entering an environment, then create a NDC;

2. The information of the NDC is included in the log operation output;

3. Call the NDC.POP method when leaving the environment;

4. When you call the ndc.remove method when exiting from a thread to release resources.

Below is an analog record from different client requesting events, the code is as follows:

import org.apache.log4j.Logger; import org.apache.log4j.NDC; public class TestNDC {static Logger log = Logger.getLogger (TestNDC.class.getName ()); public static void main (String [] args) { LOG.INFO ("Make Sure% X IS IN Your Layout Pattern!"); // Example of an IP address from the client String [] IPS = {"192.168.0.0.10", "192.168.0.27"}; for (int i = 0; i

Note that you must add% x in the layout format in the configuration file. The system is output as follows:

INFO - Make sure% x is in your layout pattern INFO 192.168.0.10 -! A NEW client connected, who's ip should appear in this log message.INFO 192.168.0.27 - A NEW client connected, who's ip should appear in this log message. INFO - Finished.

Use log4j or JDK Logging API

From JDK 1.4.0, a java.util.logging package is introduced. Although the Log4j team worked as a "Java Community Process) using Log4J as a" standard "log API of JDK 1.4, although the final stage of Merlin's development has reached the final stage due to Sun's log API specification," Merlin's development has reached the final stage, The main API is not allowed to make changes to the main API, but log4j has an important impact on new log APIs. So, should we use LOG4J or a java.util.logging package? The following is only a simple comparison to both. 1. LOG4J is more mature, from October 1999, has been 3 years since October 1999, and has been mature in many projects. The Logging package in JDK is introduced after 1.4 and cannot run in the JDK 1.3. Log4j can be well running all versions after JDK 1.1.

2. LOG4J has been ported to a variety of environments, including LOG4C (C), LOG4CPP (C ), Log4Perl (Perl), Log4Net (.NET), etc. In these environments, you can feel almost consistent configurations and ways. This is the Logging API in the JDK can't match.

3. LOG4J also has a more powerful format system that enables a simple mode when the record is output. However, it does not increase the class and leads to the expansion of the formatting tool. Numerous additional procedures and processors make the log4j packets into a great choice, all you need can be implemented.

4. Log4j has made the greatest optimization in performance.

Logging API is sufficient for simple use, but it lacks a number of log4js. So, if you need a powerful logging mechanism, you should use the log4j; if you just need some simple control or file log, you can use the Logging API already built in JDK.

Although log4j and JDK Logging APIs are a competitive relationship, when the Logging API is also discussed in JCP (JSR47), the two have begun to affect each other.

FAQ

1. How to make log4j use the specified profile

Implant the system properties when you start your application. For example, you can put the above log4j.properties file in the relative path of / Properties, and renamed Log.properties, if log4j can find this configuration file and initialize properly, you need this program:

D: /../ java -dlog4j.configuration =. /Properties/log.properties YourAppname

Why do you have to use the system properties, not specified in the configuration file? Obviously, if it writes it to the configuration file, the log4j is late when it is read.

2. How to check the log4j configuration process

You can set the system attribute log4j.debug = true like 1, thereby opening the LOG4J's Verbose mode, which outputs the Log4j initialization process, which will have a more detailed understanding of the Log4J. Below is an example of Log4J startup information:

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

New Post(0)