Logger.getlogger () and Logfactory.getlog ()

Source: Internet
Author: User

The difference between Logger.getlogger () and Logfactory.getlog ():
1.logger.getlogger () is logging using the Log4j method, 2. Logfactory.getlog () is from Apache's common-logging package.

One: Why use both commons-logging and log4j?
The purpose of commons-logging is to provide a unified interface for "All Java log implementations", its own log function is usually weak (only a simple simplelog?), so it is generally not used alone. The log4j feature is very comprehensive and powerful, and is currently the first choice. I found that almost all of the Java open source projects would use log4j, but I also found that all projects that used log4j would also use Commons-loggin at the same time. I think people don't want their projects to be too tightly tied to log4j. Another reason I can think of "using commons-logging and log4j at the same time" is to simplify usage and configuration.

Two: What can commons-logging do for us?
Provide a unified log interface, simple operation, while avoiding the project and a log implementation system tightly coupled, very thoughtful to help us automatically select the appropriate log implementation system (this is very good!). It doesn't even need to be configured here to see how it "' very thoughtful ' helps us ' automatically select ' appropriate ' Log implementation system ':

1) First find its own configuration file under Classpath commons-logging.properties, if found, then use the Log implementation class defined therein;

2) If the Commons-logging.properties file is not found, find out if the system environment variable ORG.APACHE.COMMONS.LOGGING.LOG is defined, find the LOG implementation class that uses its definition, and create a : catalina_opts environment variable, give him the value:-Dorg.apache.commons.logging.Log = Org.apache.commons.logging.impl.SimpleLog,- Dorg.apache.commons.logging.simplelog.defaultlog = Warn,

3) Otherwise, see if there are log4j packages in classpath, and if found, automatically use log4j as the log implementation class;

4) Otherwise, use the JDK's own log implementation class (JDK1.4 only after the log implementation class);

5) Otherwise, use commons-logging to provide a simple log implementation class Simplelog;

(The above order is not guaranteed to be completely accurate, please refer to the official documentation)
As can be seen, commons-logging always finds a log implementation class and finds a "most appropriate" log implementation class whenever possible. I said it was "very sweet" actually because:
1, can not need configuration files;
2, automatic judgment there is no log4j package, there is automatic use;
3, the most pessimistic situation also always guaranteed to provide a log implementation (Simplelog).


As you can see, commons-logging is very friendly to programmers and log4j.

In order to simplify the configuration commons-logging, the commons-logging configuration file is not used, and the commons-logging-related system environment variables are not set, but only the log4j jar package can be placed in Classpash. In this way, it is easy to complete the fusion of commons-logging and log4j. What if you don't want to use log4j? Simply remove the log4j jar package from the classpath. It's so easy!

How should the code be written?
We do the following three jobs in the "every" class that requires the output log information:

1, import all the required commongs-logging class:

Import Org.apache.commons.logging.Log;
Import org.apache.commons.logging.LogFactory; If you want to simplify, you can also line up two lines:

Import org.apache.commons.logging.*;2, defining a private static class member of the Org.apache.commons.logging.Log class in its own class:

private static log log = Logfactory.getlog (youclassname.class); Note that the static member is defined here to avoid producing multiple instances.

The parameters of the Logfactory.getlog () method use the class of the current classes, which is by far the best way to be considered. Why not write Logfactory.getlog (This.getclass ())? Because the static class member does not access the this pointer!

3. Use the member method of the Org.apache.commons.logging.Log class to output log information:

Log.debug ("111");
Log.info ("222");
Log.warn ("333");
Log.error ("444");
Log.fatal ("555");    here the log, which is the class member variable defined in the second step above, The type is org.apache.commons.logging.Log, and with this class's Member method, we can output log information of different nature to the destination (where is the destination?). Depending on the configuration, it may be stdout, it may be a file, it may be sent to the mail, or even send a text message to the phone ... See below for an introduction to log4j.properties):

Debug () Output the "debug" level of log information;
info () Output log information at the "Information" level;
Warn () Output log information at the "Warning" level;
Error () Output log information at the "wrong" level;
Fatal () Outputs log information at the "Fatal error" level; Depending on the nature, log information is usually divided into different levels, from low to High:
Debug (Debug) information (info), warning (WARN), error (Error), fatal error (FATAL).
Why divide the log information into different levels? This is actually convenient for us to control it better. For example, through the log4j configuration file, we can set "output debug" and the above level of log information (that is, "debug" "Information" "Warning" "Error" "Fatal error"), which may be useful for project developers, we can also set the output "warning" and the above level of log information "(that is," warning "Error" "Fatal error", which may be useful for project end users.

Only literally, it can be concluded that the most commonly used should be debug () and info (), while warn (), error (), and fatal () are used only after the corresponding event has occurred.

As can be seen from the above three steps, the log interface using commons-logging is very simple and does not need to remember too many things: only two classes of log, Logfactory, and two classes of methods are very few (the latter only use a method, The former often uses only a few of the three steps listed above, and the parameters are very simple.

The method described above is currently used in general, can be said to be standardized method, almost all people are so used. If you do not believe, or want to confirm, go to download a few well-known Java Open source project sources code to see it.

Here is the code for a complete Java class:

Package liigo.testlog;
Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;
public class testlog{
private static log log = Logfactory.getlog (Testlog. Class);
public void Test () {
Log.debug ("111");
Log.info ("222");
Log.warn ("333");
Log.error ("444");
Log.fatal ("555");
}
public static void Main (string[] args) {
Testlog Testlog = new Testlog ();
Testlog.test ();
}
}
As long as the commons-logging jar package is guaranteed to be in Classpath, the code above will certainly be compiled smoothly. What is the result of its execution? I'm afraid there will be a big difference, please keep looking down.
Where is log4j? Does it work?
It should be noted that the source code we gave above does not involve log4j--, which is exactly what we want, and that is one of the goals that commons-logging to achieve.
But, how can let log4j play its role? The answer is simple, just meet the "log4j jar package" in classpath. As already mentioned, Commons-logging will automatically discover and apply log4j. So as long as it exists, it works. (Does it not exist?) Nature does not work, commons-logging will select other log implementation classes. )

Note: The configuration file log4j.properties is required for log4j. If the configuration file is not in Classpath or is not configured, a run-time exception will be thrown.
In this way, to correctly apply the LOG4J output log information, the role of log4j.properties is very important. Fortunately, the file has a generic template, a copy (slightly modified) can be used. In almost every Java project directory there will be a log4j.properties file that can be downloaded from several Java Open source project sources. At the end of this article is also attached to a template nature of the log4j.properties file, directly copied in the past can be used, or according to their own needs slightly modified. The log4j.properties file will be described appropriately in the following sections.
Here is a hint: if you do not use commons-logging, only using log4j alone, the operation is a little more cumbersome, because log4j need a little more initialization code (compared to commons-logging):

Import Org.apache.log4j.Logger;
Import Org.apache.log4j.PropertyConfigurator;
public class Testlog4j {
static Logger Logger = Logger.getlogger (testlog4j. Class); First step
public static void Main (String args[]) {
Propertyconfigurator.configure ("Log4j.properties"); Second Step
Logger.debug ("Here is some debug"); Third Step
Logger.info ("Here is some info");
Logger.warn ("Here is some warn");
Logger.error ("Here is some error");
Logger.fatal ("Here is some fatal");
}
}


But there is one more line. But that at least suggests that quoting Commons-logging does not complicate the problem, but rather makes it simpler. It's less than 2 here. This also validates the previous conclusion.

Summarize
Both the commons-logging and log4j jar packages are placed under Classpath, and the log4j configuration files are placed in Classpath, both of which can work well together. The use of log4j with commons-logging as a log system, is currently the Java field is very popular mode, using very very common. The combination of the two results is: simple + powerful.

Commons-logging provides a concise, unified interface, no need for additional configuration, simple;

log4j function is very comprehensive and powerful;

Commons-logging only to log4j (of course, including other log implementations) as a layer of packaging, the specific log output is transferred to the back of the log4j to deal with, and log4j although did all the things, but the green leaves, never to show.

It's a perfect match.

Logger.getlogger () and Logfactory.getlog ()

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.