Java Project Test log4j

Source: Internet
Author: User
Tags log log print format log4j

I. Basic PRIMER 1.1 Download and install

Download the appropriate log4j-1.2.15.jar (and download other versions) to provide a Web site to download the jar package (http://search.maven.org/)

Create a new Log4j.properties file:

#配置根Loggerlog4j. rootlogger=Info, RF   #info代表的是日志输出的级别log4j. appender.rf=  Org.apache.log4j.RollingFileAppender  #文件大小到达指 # fixed size when generating # A new file log4j.appender.rf.file=  example.loglog4j.appender.rf.maxfilesize=100kblog4j.appender.rf.maxbackupindex=1  log4j.appender.rf.layout=org.apache.log4j.patternlayoutlog4j.appender.rf.layout.conversionpattern=%d{ YYYY-MM-DD HH:mm:ss}%p [%c]-%m%n# Add log log under a package log4j.logger.com.lxy.io.file=debug, stdoutlog4j.appender.stdout=org.apache.log4j.consoleappenderlog4j.appender.stdout.layout=  org.apache.log4j.patternlayout# Pattern to output the caller 's file name and line NUMBER.LOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD HH:mm:ss}%p [%c]-%m% Nlog4j.additivity.com.lxy.io.file=true # If False, the output of the root root setting specified above       will be disabled 
1.2 Code examples

The project structure is as follows:

If the log4j.properties is placed at the root of the project, load:

Propertyconfigurator.configure ("Lo4j.properties");

If placed in the SRC directory, load the folder with the class output path, for example:

Propertyconfigurator.configure ("Bin/lo4j.properties");

To set the log contents:

 Public class logtest{    static Logger Log=logger.getlogger (filetest.  Class);      Public Static void Main (string[] args) {        propertyconfigurator.configure ("lo4j.properties");        Log.debug ("===========debug information ===============");        Log.info ("===========info information ===============");        Log.error ("===========error information ===============");}    }
Second, log4j detailed

LOG4J consists of three important components: the priority of the log information, the output destination of the log information, and the output format of the log information. The priority of log information is from high to low, and, respectively, to ERROR WARN Specify the INFO DEBUG importance of this log information, the output destination of the log information specifies whether the log will be printed to the console or the file, and the output format controls the display of the log information.

2.1. Define the configuration file

LOG4J supports two configuration file formats, one in XML format and one Java attribute file (key = value). Here's how to use the Java attributes file as a configuration file:

2.1.1 Configuring the root Logger

Its syntax is:

Log4j.rootlogger = [level], Appendername, Appendername, ...

Where level is the priority of logging, which is divided into,,,,, OFF FATAL ERROR WARN INFO DEBUG , ALL or levels that you define. LOG4J recommends using only four levels, with priority levels from high to low, respectively,,,, and ERROR WARN INFO DEBUG . By defining the level here, you can control the switch to the appropriate level of log information in your application. For example, if the level is defined here INFO , the DEBUG log information for all levels in the application will not be printed. Appendername refers to where the B log information is exported. You can specify multiple output destinations at the same time.

2.1.2 Configuring log information Output destination

Output Destination Appender, whose syntax is:




Log4j.appender.appenderName.option = Valuen

Among them, LOG4J provides the following types of Appender:

    • Org.apache.log4j.ConsoleAppender (console)
    • Org.apache.log4j.FileAppender (file)
    • Org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)
    • Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size)
    • Org.apache.log4j.WriterAppender (send log information in stream format to any specified location)
2.1.3 Format of configuration log information (layout)

Its syntax is:




Log4j.appender.appenderName.layout.option = Valuen

Among them, log4j offers the following types of layout:

    • Org.apache.log4j.HTMLLayout (Layout in HTML table Form)
    • Org.apache.log4j.PatternLayout (flexibility to specify layout mode)
    • Org.apache.log4j.SimpleLayout (contains level and information strings for log information)
    • Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

log4j formats the log information in a print format similar to the printf function in C, with the following printing parameters:

%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, for example:%d{yyyy-mm-dd hh:mm:ss,sss}, output similar to: 2002-10-18 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.

%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

2.1.5 Precautions

Classloader.getsystemresource ("") the file loaded is below the path where the bin is located

  PropertyConfiguratoris a class in log4j used to initialize the configuration of log4j

  ClassLoaderThe GetResource ("") method of the class can get the absolute path of the current classpath, which is the ability of all Java programs to have the greatest adaptability!

Java Project Test 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.