Log4j's configuration is now looking at the meaning of log4j.properties profile. The first line specifies the level of the root Logger is Debug and outputs this specified to A1. A1 is the second line defined org.apache.log4j.consoleAppender, which indicates that the A1 is output to the console. The third line specifies the format of the output to the A1 to org.apache.log4j.patternlayout. The fourth line specifies the conversion mode output to the A1 format to org.javaresearch.log4j.testlog4j. Many mature server class software log information will be output to the console while outputting to log file check. This feature can be easily accomplished by modifying the profile without changing any code without changing any code. The relevant configuration files are as follows:
#### Use Two appenders, One to log to console, Another to log to a file
Log4j.rootcategory = Debug, Stdout, R
# Print Only Messages of Priority Warn or Higher For Your Category
Log4j.category.Your.category.Name = WARN
#### First appender Writes To Console
Log4j.appender.stdout = org.apache.log4j.consoleAppender
Log4j.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 file
Log4j.Appender.r = org.apache.log4j.rollingfileappender
Log4j.Appender.r.file = example.log
# Control The Maximum log file size
Log4j.Appender.r.maxfilesize = 100kb
# Archive log files (One Backup File Here)
Log4j.Appender.r.maxbackupindex = 1
Log4j.Appender.r.Layout = org.apache.log4j.patternlayout
Log4j.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. In web applications, where should I configure the log4j? First of all, the 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, the code is 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");
/ / Read the log4j profile from the servlet parameter
IF (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 {}
}
init-param>
servlet>
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 certainly affect the operating efficiency of the system, 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 is usually different from different client requests by different threads in a multi-user concurrent environment. 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 an NDC; 2. The log operation output includes NDC information; 3. Leaving The NDC.POP method is called when the environment is called; 4. Call the NDC.Remove method when exiting from a thread to release resources. Here is an example of analog records 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!");
/ / An example of obtaining an IP address from the client
String [] IPS = {"192.168.0.10", "192.168.0.27"};
For (int i = 0; i { // put the IP in NDC NDC.PUSH (IPS [I]); Log.info ("A New Client Connected, WHO'S IP Should APPEAR in this log message."); NDC.POP (); } Ndc.remove (); Log.info ("Finished."); } } Note that you must add% x in the layout format in the configuration file. The system output is 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, introduced a java.util.logging package. 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 implant the system properties when you start your application using the specified profile. 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 that the configuration process of the log4j can be similar to 1, set the system properties log4j.debug = true, thereby opening the log4j's Verbose mode, which outputs the LOG4J initialization process, which will have a startup of log4j More detailed understanding. Below is an example of log4J startup information: log4j: trying to find [log4j.xml] Using Context ClassLoader Sun.misc.launcher $AppClassLoader@92e78c. Log4j: Trying to find [log4j.xml] Using sun.misc.launcher $ExtClassLoader@9fbe93class Loader. Log4J: Trying to find [log4j.xml] using classloader.getsystemResource (). Log4j: Trying to find [log4j.properties] Using Context ClassLoader Sun.misc.launcher $AppClassLoader@92e78c. Log4j: using url [file: / d: /java/logging/src/log4j.properties] for automatic log4j CONFIGURATION. Log4J: Reading Configuration from Url file: / e: /java/logging/src/log4j.properties Log4j: Parsing for [root] with value = [debug, A1]. Log4j: Level token is [debug]. Log4j: category root set to debug Log4j: Parsing appender named "a1". Log4J: Parsing Layout Options for "A1". Log4j: setting property [conversionPattern] To [% D% L%-5P% C [% T] -% m% n]. Log4j: End of paarsing for "a1". Log4j: parse "a1" options. Log4j: finished configuring. ... // The following is the application log information, omitted.