Java log Technology Summary (log4j, commons-logging ,.....)

Source: Internet
Author: User
Tags java util
Preface

There are many ways to record logs in Java,

1. The simplest method is system. Print. Out, And err print messages directly on the console.

2. java. util. Logging; after JDK 1.4, the log API is provided to write logs to files.

3. log4j: the most powerful way to record logs. You can configure the log destination and format by configuring the. properties or. xml file.

4. commons-logging is the most comprehensive and common logging method. It is often used in combination with log4j.

Java. util. Logging -- JDK Logging Method

System. Print,

Let's take a look at the example of using logging logs in Java APIs:

/**    * @author oscar999    * @date 2013-8-1 * @version V1.0    */package com.oscar999.log;import java.io.IOException;import java.util.Date;import java.util.logging.FileHandler;import java.util.logging.Formatter;import java.util.logging.Level;import java.util.logging.LogRecord;import java.util.logging.Logger;public class TestLogJava {public static void main(String[] args) throws IOException{Logger log = Logger.getLogger("tesglog");log.setLevel(Level.ALL);FileHandler fileHandler = new FileHandler("testlog.log");fileHandler.setLevel(Level.ALL);fileHandler.setFormatter(new LogFormatter());log.addHandler(fileHandler);log.info("This is test java util log");   }}class LogFormatter extends Formatter {@Overridepublic String format(LogRecord record) {Date date = new Date();String sDate = date.toString();return "[" + sDate + "]" + "[" + record.getLevel() + "]"+ record.getClass() + record.getMessage() + "\n";}}

Code and test in eclipse.

First define a logeer instance and set the log level. Then add a filehander to write the log to the file. When writing a file, define a logformatter to render the log format.

By default, logs are printed to the console. After filehandler is added, the file will be written at the same time. If no path is specified, the log file is located under the project root path.

Log4j Logging Method

Log4j is a jar file provided by Apache to record logs.

Download path:

Http://logging.apache.org/log4j/1.2/download.html

Here we need to do a little more:

1. Download the jar package of log4j and add it to the Lib package of the project (add it to the build path of the project ).

2. Configure log4j. properties and put it under the root path of the project. (You can also put it in another path, which needs to be specified during reading)

Take a look at the next configuration instance:

log4j.rootLogger=debug,stdout,logfilelog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%nlog4j.appender.logfile=org.apache.log4j.RollingFileAppenderlog4j.appender.logfile.File=logfile.loglog4j.appender.logfile.MaxFileSize=512KBlog4j.appender.logfile.MaxBackupIndex=3log4j.appender.logfile.layout=org.apache.log4j.PatternLayoutlog4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

The log output level debug is specified here.

Stdout, logfile specifies the log output destination. The two names can be obtained at will, for example, A or B. The actual configuration is org. Apache. log4j. consoleappender and rollingfileappender, which are used to specify the console or file.

In addition, the output format and generated file rules are also specified.

3. Test the Java File

/**    * @author oscar999    * @date 2013-8-1 * @version V1.0    */package com.oscar999.log;import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;public class TestLog4j {public static void main(String[] args) {// 1. create logLogger log = Logger.getLogger(TestLog4j.class);// 2. get log config filePropertyConfigurator.configure("log4j.properties");// 3. start loglog.debug("Here is some DEBUG");log.info("Here is some INFO");log.warn("Here is some WARN");log.error("Here is some ERROR");log.fatal("Here is some FATAL");}}

Configuration is a little complicated, but the code is much simpler.

Commons-logging

Commons-logging is also the log JAR file provided by Apache.

:

Http://commons.apache.org/proper/commons-logging/download_logging.cgi

You may ask why does log4j provide commons-logging? What is the difference between the two?

In fact, we can see from the name of commons-logging. This should be a log sharing interface. In fact, it does play such a role,

When you use the logfactory Of Commons-logging to obtain the log processing class:

1) First find your own configuration file commons-logging.properties under classpath, if found, use the defined log implementation class;
2) If the commons-logging.properties file is not found, you can use the defined log implementation class to find the system environment variable org. Apache. commons. Logging. log that has been defined;
If you can create an environment variable named catalina_opts in tomact
Value:-dorg. apache. commons. logging. log = org. apache. commons. logging. impl. simplelog-dorg. apache. commons. logging. simplelog. defaultlog = warn
3) Otherwise, check whether the classpath contains a log4j package. If any package is found, log4j is automatically used as the log implementation class;
4) Otherwise, use the JDK's own log implementation class (the log implementation class is available only after jdk1.4 );
5) Otherwise, use commons-logging to provide a simple log implementation class simplelog;

First look at an instance in the first way, configure the commons-logging.properties, and use log4j to record logs.

Note: To use commons-logging to record logs with log4j, you must import the jar package of log4j to the project.

1. Import the jar packages of log4j and commons-logging.

2. Configure the commons-logging.properties and log4j. properties, and put it under the classpath (that is, the src directory) of the project)

Note: When Using log4j separately, log4j. properties is stored in the project root directory by default.

The content of log4j. properties is exactly the same as above.

Look at the commons-logging.properties Configuration

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

In one sentence, specify to use log4j

3. Test code:

/**   * @author oscar999   * @date 2013-8-1* @version V1.0   */package com.oscar999.log;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class TestLogCom {static Log log = LogFactory.getLog(TestLog.class);public static void main(String[] args) {log.debug("Here is some DEBUG");log.info("Here is some INFO");log.warn("Here is some WARN");log.error("Here is some ERROR");log.fatal("Here is some FATAL");}}

Besides using log4j, you can also configure

-Org. Apache. commons. Logging. impl. Jdk14loggerUse jdk1.4. -Org. Apache. commons. Logging. impl. Log4jloggerUse log4j. -Org. Apache. commons. Logging. impl. LogkitloggerUse aveon-logkit. -Org. Apache. commons. Logging. impl. SimplelogCommon-logging comes with the log implementation class. It implements the log interface and outputs all log messages to the system error stream system. Err. -Org. Apache. commons. Logging. impl. NooplogCommon-logging comes with the log implementation class. It implements the log interface. The log output method does not perform any operations.

Summary

One of the above

3) Otherwise, check whether the classpath contains a log4j package. If any package is found, log4j is automatically used as the log implementation class;

The project imports the jar package of log4j and commons-logging at the same time, without configuring the commons-logging.properties, you only need to configure log4j. properties in classpath to record logs using log4j. This is also the method of using a large number of logs.

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.