Everyone is often inevitably to use some log operations, such as debugging information, runtime logging and auditing. The survey shows that the log code accounts for 4% of the total code. Usually everyone can simply use the system.out.println () statement to output log information, but there will be some judgment, such as:
IF (somecondition) {
System.out.println ("Some Information.");
}
These judgments have caused a large number of output statements in normal program logic. These judgments written under the development phase are only for debug statements, and they need to find and remove when development is completed. After deployment, especially in some enterprise applications, further debugging is often required, and even more troublesome. So, we need a complete set of flexible, configurable log tools. Log4j is an excellent choice. Log4j is a subproject under the Apache Software Foundation Jakarta project, which is an excellent log kit written in Java. By the log4j, it is convenient, flexible, and flexibly controls the opening or closing of the log information of any particle size, and then outputs the log information to one or more required places where the custom format is used. Also, log4j has a smooth learning curve that can learn its simple use within three minutes. With in-depth use, you will find that the Log4J function is powerful, almost all of the needs of the log.
Get started
First look at a code, see how easy to get the log4j, the code is as follows:
Package org.javaresearch.log4j;
Import org.apache.log4j. *;
Public class testlog4j {
Static logger log = logger.getlogger (Testlog4j.class.getname ());
Public static void main (string args []) {
BasicConfigurator.configure ();
// Logging various methods
Cat.debug ("START of Main ()");
Cat.info ("Just Testing A Log Message with Priority Set to Info");
Cat.Warn ("Just Testing A Log Message with Priority Set To Warn");
Cat. Error ("Just Testing A Log Message with Prior Set to Error");
Cat.fatal ("Just Testing A Log Message with Priority Set To Fatal";
// Another inconvenient format
Cat.log (Priority.debug, "Testing a log message") and a alternate form
"" End of main (). ");
}
}
Save this code in a directory, compile operation (Note To put the log4j-1.2.7.jar into the path), the program output is as follows:
0 [main] debug testlog4j - start of main ()
10 [main] info testlog4j - Just Testing a log message with priority set to info
20 [main] WARN TESTLOG4J - JUST TESTING A LOG Message with priority set to warf4j - just testing a log message with prior set to error
30 [main] Fatal Testlog4j - Just Testing a log message with priority set to fatal
40 [Main] Debug Testlog4j - Testing a log message USE A Alternate Form
50 [main] debug testlog4j - end of main ().
First explain the significance of the output results above. The first number refers to the number of milliseconds experienced by the program to run to the log statement (to do a little running efficiency analysis is also good), "[main]" is a thread that occurred in the log event, and then "debug", " INFO "and other information is the priority of the corresponding log information," Testlog4 "is the instance name of the current Logger, and finally the log information. In this program, a basic configuration class BasicConfigurator provided by log4j is used to initialize Log4j. But don't do this when practical use, because this is a bit "hard" encoding. In the future, if you want to modify the log4j configuration, you need to modify, recompile the code, which is usually not hoped. Typically, we all provide a file called log4j.properties. When you call to log4j for the first time, Log4j will locate this file in the class path and read this file. This profile tells the log4j to do what kind of information, what kind of information, and where it is output. Let's take a look at an example of a simple log4j.properties profile, the code is as follows:
Log4j.rootlogger = Debug, A1
Log4j.Appender.a1 = org.apache.log4j.consoleAppender
Log4j.Appender.a1.Layout = Org.apache.log4j.patternlayout
Log4j.Appender.a1.Layout.ConversionPattern = "% -4r [% T]% -5p% C% X -% M% N
Store the above content as log4j.properties and put it in the same directory with TestLog4j.class (of course, you can also put any other directory as long as the directory is included in the classpath). The meaning of each line in these configuration files, in the next chapter, there will be detailed descriptions, and now you can skip. Now you can comment out the "BasicConfigurator. Configure ();" statement in the above program, then use the log4j.properties attribute file to complete the log4j configuration, recompile, run, and get the same result as above. What is the benefit of this? Now I will prestimate some of the flexible and powerful functions of log4j. For example, the system is going online, wants to output some warnings and error messages, then only need to modify "log4j.rootcategory = debug, A1" in the log4j.properties file, and then set the lowest level of the log output is WARN, set to " Log4j.Root category = warn, a1 ". At this point, you don't need to modify any code, re-run the system, and the output is turned:
20 [main] WARN TESTLOG4J - JUST TESTING A LOG Message with priority set to warf4j - just testing a log message with prior set to error
30 [main] Fatal Testlog4j - Just Testing a log message with priority set to fatal
Principle analysis
Log4j has three major components that are loggers, an output source (Appenders) and Logouts. The logger writes the log information into one or more output sources according to the format specified in the layout. Output source can be a console, text file, XML file, or socket, or even write information to a Windows event log or send it via email, which requires the corresponding class to handle, these related classes are consolerappender, FileAppender, SocketAppender, NTEVENTLOGAPPENDER and JMSAPPENDER. The logger first let us see the logger class, the code is as follows:
Package org.apache.log4j;
Public class logger {
// Creating and recovering methods
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 print method
Public void log (level L, Object Message);
}
From this code, you can see the basic use of the Logger. First, you need to get a logger object, get the statement of the Logger object as:
Logger logger = logger.getlogger (javaloggingexample.class.getname ());
With this Logger object, you can easily output log information in the needs. For these information, the format, the output, etc., can be easily configured by the configuration file without modifying the code, which is the convenience of log4j. The hierarchy of the recorder uses log4j's Logger.getLogger () method to get an instance of a Logger. 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. One core concept in Level Log4j is the log level is in an orderly. Log4j has built-in 5 log levels:
Debug The level on the right is higher than the left. Each Logger instance has a log level. The above five output methods are corresponding to five different levels of log requests. For example, if c is a logger instance, C.info ("Some Information) is an INFO level log request. A log request will not be output, depending on the log level of the Logger instance and the comparison of the log request level. The rules are as follows: If a log request of a level Q is occurred in a Logger instance of the P level, the request is enabled when Q> = P. Let's first see example 2 code as follows: // Get a Logger instance "com.foo" Logger logger = logger.getlogger ("com.foo") // Now set the Logger level, but normal situation is not necessary to deliberately set the LGGER level because it has been completed in the configuration file. Logger.SetLevel (Level.info); Logger Barlogger = logger.getlogger ("com.foo.bar"); // Because Warn> = INFO, this request is achievable Logger.warn ("Low Fuel Level."); // Because Debug Logger.debug ("Starting Search for NEAREST GAS Station); // Logger instance "com.foo.bar" will inherit the level from "com.foo", so because INFO> = INFO, so you can implement the following request Barlogger.info ("Located Nearest Gas Station); // Because Debug Barlogger.debug ("EXITING GAS STATION SECH"); Layout log4j formatted log information in a printing format of the Printf function in the C language, and the print parameters are shown in Table 1 as follows: