JDK Log Framework Interpretation

Source: Internet
Author: User
What the log is. It is not just a bunch of System.out.println (). Remember that when you first learn Java, you will not debug, so you use System.out.println () to print the value of the variable in a critical position. Once you have the log program, it is essentially the same, and you have to manually invoke the log program's API where you need it, such as the Common Log.info (). But the advantage of using the log program is that the output is formatted, is more standardized, and can be easily imported into other destinations such as files.
The relevant classes and interfaces are located in the Java/util/logging package, and this framework logs the idea that the main includes Loggor and Appender (also known as handler) two parts (other is the details first regardless), the former embedded in the application of the supply with the call, receive the log, The form is Log.info (), and then the received log is forwarded to Appender processing, which formats the log and outputs it to the corresponding destination. A logger can correspond to multiple appender at the same time, each appender corresponding to a specific output destination. Stolen picture down face:

The example in the code is as follows:
public static void Main (string[] args) {
        Consolehandler handler = new Consolehandler ();
        Handler.setlevel (level.fine);
        Filehandler Filehandler = new Filehandler ("/home/tt.txt", true);
        Filehandler.setlevel (Level.finer);


        Logger Logger =  Logger.getlogger ("W");
        Logger.setlevel (Level.all);
        Logger.addhandler (handler);
        Logger.addhandler (Filehandler);
        Logger.log (Level.info, "hehe");
 }

The only way to get a logger object is to use the logger static method GetLogger and pass in a string parameter as the name of the object. Because it is possible to use logger in each specific class, naming it is typically a class name that uses the class directly, and the benefit is to avoid duplication. Because the logger object is generated, it will first find out if there is a logger with the same name, and some words return it directly, otherwise the new object is generated. Because each class uses the logger requirement differently, it is personalized, so try not to use the same logger.
The Appender object is defined separately and is then passed as an entry parameter to the Logger object's AddHandler method. This creates a Consolehandler object and a Filehandler object, which, by name, can be seen to output the log to the standard output, which outputs the log to the specified file. Of course, you can also define multiple Consolehandler or Filehandler objects and add them to this logger object (although it doesn't make much sense for consolehandler), after all, a logger can correspond to multiple appender at the same time.
In addition, the code also involves the log level, grading the log is a good idea, the purpose is to facilitate management, this way of thinking is very "Western." JDK, the default has the following levels of log: Off,severe,warning,info,config,fine,finer,finest,all, the level of descending, the corresponding log more and more detailed, the importance of more and more low. That is, off will not be any log, and all will output all logs. The level that a log belongs to is specified by the developer when calling the logger log method, and the first parameter of the method requires the level of a log to be specified, and the second parameter is the specific log content.
Both logger and Appender can have their own filters to filter the logs that they output downstream. The principle of filtration is to output only the level of higher or equal to the configuration level of the log, such as the configuration level is info, then the level below the info log will not be sent downstream. In code, both logger and Appender call the Setlevel method to set the filtering level.

Such a lap down, in order to play a "hehe", the code is too bloated, far from System.out.println ("hehe") concise and efficient. I was just about to debug the source code, essentially the same routine:

First Logger.log the core code in the () method:

while (logger!= null) {
            final handler[] loggerhandlers = Issystemlogger
                ? Logger.accesscheckedhandlers ()
                : Logger.gethandlers ();
            for (Handler handler:loggerhandlers) {
                handler.publish (record);
}

Its logic is to loop through all the Appender and call its publish method. This method eventually invokes the publish method of the Streamhandler class, at the heart of this method:

try {
            if (!doneheader) {
                writer.write (Getformatter (). GetHead (this));
                Doneheader = true;
            }
            Writer.write (msg);
And who is this writer? For Consolehandler:

Public Consolehandler () {
        sealed = false;
        Configure ();
        Setoutputstream (System.err);
        sealed = true;
}


The JDK Log framework then provides the developer with a configuration file to reduce the amount of code. If the personalized requirements of the logger is not high, or the program most of the logger is the same routine, then you can use the configuration file to handle the log, the need to personalize the code on its own, the priority of the code is higher than the configuration file. The configuration file name is Logging.properties, located in the ${java_home}/jre/lib directory, as follows:

handlers= java.util.logging.ConsoleHandler
. level= INFO
# Default file output is in user ' s home directory.
Java.util.logging.FileHandler.pattern =%h/java%u.log
java.util.logging.FileHandler.limit = 50000
Java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = Java.util.logging.XMLFormatter
# Limit The message that are printed on the console to INFO and above.
Java.util.logging.ConsoleHandler.level = INFO
Java.util.logging.ConsoleHandler.formatter = Java.util.logging.SimpleFormatter
# For example, set the Com.xyz.foo logger to only log SEVERE messages:
com.xyz . Foo.level = SEVERE
So what does this configuration file do? First: Specify what kind of Appender it will have for each logger (each class can have only one), which is configured by handlers property; second: Specify specific settings for each Appender class, such as log level, log format, etc. Third: Specifies the log level of each logger, which is specified by the. Levels property of the logger name, as in the example, I don't know if I can specify any other attributes, and the source code is not read.

Finally, there is a global log level configuration:
. level= INFO
This configuration only works if a logger or appender is not configured at its own level, but if logger or appender has its own configuration, then the global configuration will be overwritten, such as the following sentence:
Java.util.logging.ConsoleHandler.level = INFO

Note that this configuration file is the default, that is, you can define your own personalization profile, and then when you run your Java program, Using the Java.util.logging.config.file parameter to specify the location of the file, Logging.properties also gives an example:
Java-djava.util.logging.config.file=myfile

This also explains the problem that the configuration file is for the entire Java program, such as Tomcat is a Java program, the Web application running on it is only part of the program, so each Web application will also share the configuration of the log. But if a Web application wants to have its own unique log configuration, it's cumbersome, which is not enough for the JDK's own log framework, so Tomcat has developed its own logging system.

Finally, say layouts, forget it or not to say.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.