Use of the Java Standard log tool log4j (source code)

Source: Internet
Author: User
Tags print format log4j

Source code Download

Log4j is the de facto Java standard logging tool. Whether to use log4j to a certain extent can be said to be a measure of a developer is a qualified Java programmer standards. If you are a Java programmer, if you are not using log4j, you really need to read this article. Many friends reflect the need to write the program log, but do not know how to write to log files, and Java this aspect of the information does not seem to be many. As described in how to write the Log4j.xml log configuration file. This article details how to use log4j in a project, and attaches an example of the nature of the code.
Why log4j?
Some friends like to use System.out.println (String msg); Statement to debug your code. This is really a good debugging tool. But with the end of the project, or the resolution of the problem, these statements need to be pulled out by hand and manually deleted? "How to delete all System.out.println statements at once", this post of the netizen encountered such a problem.
All are removed clean, the question comes again: If later appeared the problem, how to do? Is it added again, the problem is resolved after finding it again to delete?
The above problems and contradictions can be solved well by using log4j. The log4j has a log level that controls whether logging is logged. Its low-to-high levels are as follows:
All < DEBUG < INFO < WARN < ERROR < FATAL < OFF
The purpose of grading logs is to be flexible to configure. For example, if the log level is limited to debug, the info, WARN, ERROR, FATAL, and OFF are logged, including debug, and if the level is defined as info, then the log of the following level, such as debug, will not be logged. For example, the following code:

[Java]View PlainCopyprint?
    1. Logger log = Logmanager.getlogger (HelloWorld.   Class);
    2. Log.info ("info gets logger object through Class object");
    3. Log.debug ("Debug uses class object to get Logger object");
    4. Log.warn ("warn obtains logger object through Class object");

If your log4j is defined as output to the console and the log level is defined as INFO, then execution to the above statement block will output the following log information:
18:07:37,237 Infohelloworld:32-info to get logger objects through class objects
18:07:37,245 Warnhelloworld:34-warn to get logger objects through class objects
Specific example authors have uploaded to the attachment, interested friends can go to download down to see. Limited to time, the example shows just how to output log information to the console. Of course, logs can also be exported to files, databases. The author argues that if you figure out the sample code, for other smart readers, you can refer to Log4j's API to get it done.
How to log4j?
First step: Download the LOG4J toolkit
Official website address: http://logging.apache.org/log4j/1.2/index.html. In the left-hand menu bar, documentation JavaDoc is log4j's online API document. We click Get log4j 1.2 under the Download to enter the download page, the latest version is 1.2.15, click Apache-log4j-1.2.15.zip to download the file, extract the log4j source code, sample code, installation instructions and log4j Jar Package (Log4j-1.2.15.jar).
Step Two: Import the log4j jar package into the project
Author Development IDE is Eclipse, right click on project name, build path, Configure build path, Add External JARS to find the log4j-1.2.15 you extracted. Jar and select it. Are you sure.
Step Three: Edit the log4j.properties file and configure your log4j
In the SRC directory of the project, create a new log4j.properties file. The LOG4J is configured through this interface.
The log4j.properties configuration of the author in the sample code is as follows:
[Java]View PlainCopyprint?
    1. # # # Logger Configuration # # #
    2. #配置根 Logger
    3. Log4j.rootlogger=info,stdout
    4. # # Direct log messages to stdout # # # # (standard terminal output)
    5. #控制台输出
    6. Log4j.appender.stdout=org.apache.log4j.consoleappender
    7. #自定义输出布局
    8. Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
    9. #输出的格式
    10. log4j.appender.stdout.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n

Description
"Log4j.rootlogger=info,stdout" sentence: Defines the root logger configuration item. Its syntax is: level, input Terminal 1, output Terminal 2, .... The stdout represents the log output to the console.
The "log4j.appender.stdout.layout.conversionpattern=%d{absolute}%5p%c{1}:%l-%m%n" statement defines the print format. The printing parameters are as follows:
%M: The message specified in the output code.
%p: Output priority.
%r: Enter the number of milliseconds that the log information was consumed from the app boot to output.
%c: The class that the output belongs to, usually the full name of the class in which it is located.
%t: Output The name of the thread that generated the journal thread.
%n: Outputs a carriage return line break. The Windows platform is "/r/n" and Unix is "/n".
%d: the date or time of the output log time, the default format is ISO8601, it is recommended to use "%d{absolute}", this output format such as: "2007-05-07 18:23:23,500", in line with Chinese habits.
%l: The location where the output log event occurred, including the class name, the thread name, and the number of lines in the code.
Fourth Step: Log code where log records are required in the code
by Logger log = Logmanager.getlogger (the class where you want to log the code), get the Logger object, and then call its info, debug, and so on for the log output. The sample code is as follows:
[Java]View PlainCopyprint?
  1. /**
  2. * File name: Helloworld.java
  3. *
  4. * Version information:
  5. * Date: 2010-1-18
  6. * Copyright XXX Corporation 2010
  7. * All rights reserved
  8. *
  9. */
  10. Package com.defonds.log4j;
  11. Import Org.apache.log4j.LogManager;
  12. Import Org.apache.log4j.Logger;
  13. /**
  14. *
  15. * Project Name: testlog4j
  16. * Class Name: HelloWorld
  17. * Class Description: Log4j Test class
  18. * Create Person: defonds
  19. * Created time: 2010-1-18 02:58:18
  20. * Modified by: Defonds
  21. * Modified time: 2010-1-18 02:58:18
  22. * Modify NOTES:
  23. * @version
  24. *
  25. */
  26. Public class HelloWorld {
  27. public static void Main (string[] args) {
  28. Logger log = Logmanager.getlogger (HelloWorld.   Class);
  29. Log.info ("info gets logger object through Class object");
  30. Log.debug ("Debug uses class object to get Logger object");
  31. Log.warn ("warn obtains logger object through Class object");
  32. }
  33. }

Again: This example just lets a friend who hasn't used log4j get an entry-level understanding of log4j powerful logging capabilities not only with this. More log4j of the log function, but also need readers in the project to know their own firsthand.

Use of the Java Standard log tool log4j (source code)

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.