Logging using commons-logging and log4j

Source: Internet
Author: User

One, why use commons-logging+log4j?

Commons-logging and log4j are open source projects under Apache. The purpose of commons-logging is to provide a unified interface for "All Java log implementations" that decouple the project from the Log Implementation tool, its own log function is weak (only a simple simplelog), so it is generally not used alone. The log4j feature is very powerful and is currently the most mainstream Java logging tool. Using both to avoid tightly coupling projects with log4j, users can easily switch to other logging tools while using Log4j's powerful features.

Two, commons-logging how to automatically select the appropriate log implementation tool?

When we use the Commons-logging+ Log Implementation tool, our code only needs to deal with Commons-logging, commons-logging to choose the appropriate log implementation tool. Here we look at how Commons-logging chooses to implement the tool:

first , look for your own configuration file commons-logging.properties under Classpath, and if found, use the log implementation class defined in it:

1.org.apache.commons.logging.log=org.apache.commons.logging.impl.simplelog this configuration, Commons-logging will use Commons-logging's Simplelog

2.org.apache.commons.logging.log=org.apache.commons.logging.impl.log4jlogger This configuration, commons-logging will choose to use log4j

3.org.apache.commons.logging.log=org.apache.commons.logging.impl.jdk14logger This configuration, commons-logging will choose the JDK logger

Two, if the commons-logging.properties file is not found, find out if the system environment variable ORG.APACHE.COMMONS.LOGGING.LOG is defined and the Log implementation class with its definition is found

Third, Otherwise, see if there are log4j packages in classpath, and if found, automatically use log4j as the log implementation class.
Four, otherwise, use the JDK's own log implementation class (JDK1.4 only after the log implementation Class).
Five, otherwise, use commons-logging itself to provide a simple log implementation class Simplelog.
As can be seen, commons-logging always finds a log implementation class and finds the most appropriate log implementation class possible.
In order to simplify the configuration, we can not use the Commons-logging configuration file, and do not set the commons-logging related environment variables, just put log4j package into classpath can be, This completes the combination of commons-logging and log4j. If you do not want to use log4j in the future, simply remove the log4j package from the classpath.

three, how to output the log in code? 1. Import the required commons-logging class

Import Org.apache.commons.logging.Log;
Import Org.apache.commons.logging.LogFactory;

If you want to simplify, you can also do two lines together:
Import org.apache.commons.logging.*;

2. Define 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. Using static class variables to output log information

To facilitate the control of the log output, the log is divided into different levels, from low to high are debugging, information, warning, error, fatal error. This way we can only output a log above a certain level through the log4j configuration. For example, at development time we will debug (debug) and above the log all output, and when the project is working properly, set to output only warn (warning) and above the log.

1.log.debug ("Debug");
Output information-level log information
2.log.info ("Information");
Output Warning Level log information
3.log.warn ("warning");
Output Error level log information
4.log.error ("error");
Output log information for fatal error levels
5.log.fatal ("fatal");
Because we can set the level of log output through a configuration file, we don't know if a log will actually output when we write the code, such as
Log.debug ("Debug");

Depending on the nature, log information is usually divided into different levels, from low to High: Debug (Debug), information (info), warning (WARN), error (ERR), 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. Using Commons-logging Log interface is very simple, do not need to remember too many things: Only two class log, Logfactory, and two classes are very few methods, and the parameters are very simple.

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 ();
}
}

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 following article will be log4j.properties file appropriate for some introduction. About log4j the configuration of the log4j configuration is simple enough to be used in more and more applications: The log4j configuration file implements a full set of functions, such as output to console, file, rollback file, send log mail, output to database log table, custom label, and so on. One or two use is enough. Log4j.rootlogger=debug,console,a1,im Log4j.addivity.org.apache=true # Applies to the console log4j.appender.console= Org.apache.log4j.ConsoleAppender Log4j.appender.threshold=debug Log4j.appender.console.target=system.out Log4j.appender.console.layout=org.apache.log4j.patternlayout log4j.appender.console.layout.conversionpattern=[ Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n #log4j. appender.console.layout.conversionpattern=[start]%d{date}[date]%n% P[priority]%n%x[ndc]%n%t[thread] n%c[category]%n%m[message]%n%n #应用于文件 log4j.appender.file= Org.apache.log4j.FileAppender Log4j.appender.file.file=file.log Log4j.appender.file.append=false Log4j.appender.file.layout=org.apache.log4j.patteRnlayout Log4j.appender.file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n # Use this layout f or Logfactor 5 Analysis # applies to file rollback Log4j.appender.rolling_file=org.apache.log4j.rollingfileappender Log4j.appender.ROLLING_FILE. Threshold=error Log4j.appender.ROLLING_FILE. File=rolling.log Log4j.appender.ROLLING_FILE. Append=true Log4j.appender.ROLLING_FILE. MAXFILESIZE=10KB Log4j.appender.ROLLING_FILE. Maxbackupindex=1 Log4j.appender.rolling_file.layout=org.apache.log4j.patternlayout log4j.appender.ROLLING_ File.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n #应用于socket Log4j.appender.socket=org.apache . log4j. Rollingfileappender Log4j.appender.socket.remotehost=localhost log4j.appender.socket.port=5001 Log4j.appender.socket.locationinfo=true # Set up for Log Facter 5 log4j.appender.socket.layout= Org.apache.log4j.PatternLayout log4j.appender.socet.layout.conversionpattern=[start]%d{date}[date]%n%p[priority ]%n%x[ndc]%n%t[thread]%n%c[category]%n%m[message]%n%n # Log Factor 5 Appender log4j.appender.lf5_appender=org.apache.log4j.lf5.lf5appender log4j.appender.LF5_ APPENDER. maxnumberofrecords=2000 # Send log to Message Log4j.appender.mail=org.apache.log4j.net.smtpappender Log4j.appender.mail.threshold=fatal log4j.appender.mail.buffersize=10 [email protected] log4j.appender.mail.smtphost=www.wusetu.com log4j.appender.mail.subject=log4j Message [email protected] Log4j.appender.mail.layout=org.apache.log4j.patternlayout log4j.appender.mail.layout.conversionpattern=[ Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n # for database Log4j.appender.database=org.apache.log4j.jdbc.jdbcappender LOG4J.A Ppender. DATABASE. Url=jdbc:mysql://localhost:3306/test Log4j.appender.database.driver=com.mysql.jdbc.driver Log4j.appender.database.user=root log4j.appender.database.password= Log4j.appender.database.sql=insert into log4j ( Message) VALUES (' [Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n ') Log4j.appender.database.layout=org.apache.log4j.patte Rnlayout log4j. Appender. Database.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n Log4j.appender.a1=org.apache.log4j.dai Lyrollingfileappender log4j.appender.a1.file=samplemessages.log4j log4j.appender.a1.datepattern=yyyymmdd-hh '. log4j ' log4j.appender.a1.layout=org.apache.log4j.xml.xmllayout #自定义Appender log4j.appender.im = Net.cybercorlin.util.logger.appender.IMAppender Log4j.appender.im.host = mail.cybercorlin.net Log4j.appender.im.username = Username Log4j.appender.im.password = Password Log4j.appender.im.recipient = [email  Protected] Log4j.appender.im.layout=org.apache.log4j.patternlayout Log4j.appender.im.layout.ConversionPattern =[ Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n

Log4j.properties use
I. Description of the meaning of the parameter
Types of output levels
ERROR, WARN, INFO, DEBUG
Error is a critical error, mainly a program
WARN for general warnings, such as session loss
Info is the general information to display, such as login log out
Debug information for the program
Configure log information Output destination
Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
1.org.apache.log4j.consoleappender (console)
2.org.apache.log4j.fileappender (file)
3.org.apache.log4j.dailyrollingfileappender (Generate a log file every day)
4.org.apache.log4j.rollingfileappender (creates a new file when the file size reaches the specified size)
5.org.apache.log4j.writerappender (send log information in stream format to any specified location)
Configure the format of log information
Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
1.org.apache.log4j.htmllayout (Layout in HTML table Form),
2.org.apache.log4j.patternlayout (flexibility to specify layout mode),
3.org.apache.log4j.simplelayout (contains the level of log information and the information string),
4.org.apache.log4j.ttcclayout (contains information about the time, thread, category, etc.) of the log
Console options
Threshold=debug: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
Target=system.err: By default: System.out, specify output console
Fileappender Options
THRESHOLD=DEBUF: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.
Rollingfileappender Options
Threshold=debug: Specifies the lowest level of output for log messages.
Immediateflush=true: The default value is true, meaning that all messages will be output immediately.
File=mylog.txt: Specifies the message output to the Mylog.txt file.
Append=false: The default value is True, the message is added to the specified file, and false refers to overwriting the message with the specified file content.
MAXFILESIZE=100KB: The suffix can be kb, MB, or GB. When the log file reaches this size, it will automatically scroll to move the original content to the Mylog.log.1 file.
maxbackupindex=2: Specifies the maximum number of scroll files that can be produced.
log4j.appender.a1.layout.conversionpattern=%-4r%-5p%d{yyyy-mm-dd HH:mm:ssS}%c%m%n
The meaning of several symbols in the log Information format:
-X: Left-aligned when the information is output;
%p: Output log information priority, i.e. Debug,info,warn,error,fatal,
%d: the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd hh:mm:ss,sss}, output similar: October 18, 2002 22:10:28,921
%r: The number of milliseconds to output the log information from the application boot to output
%c: The class in which the output log information belongs, usually the full name of the class in which it is located
%t: Output The name of the thread that generated the log event
%l: The location of the output log event, which corresponds to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10)
%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets.
Percent: Output a "%" character
%F: The name of the file where the output log message was generated
%l: Line numbers in the output code
%M: The specified message in the output code, resulting in the log specific information
%n: Output a carriage return line break, Windows platform is "\ r \ n", Unix platform for "\ n" Output log information line-wrapping
You can add modifiers between% and pattern characters to control their minimum width, maximum width, and text alignment. Such as:
1)%20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the default is the right alignment.
2)%-20c: Specify the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-aligned.
3)%.30c: Specify the name of the output category, the maximum width is 30, if the category name is greater than 30, will be the left more than the character of the cut off, but less than 30, there will be no spaces.
4)%20.30c: If the category name is less than 20, fill in the blanks, and right-aligned, if its name is longer than 30 characters, it is truncated from the far left character.
Loading Instances




Logging using commons-logging and log4j

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.