"Turn-Organize" log4j simple explanation, configuration

Source: Internet
Author: User

LOG4J consists of three major components: Loggers,appenders and layouts.

1. Define the Log component logger

Each logger can have one or more appender, each appender representing the output destination of a log, such as the console or a file.

The syntax for configuring root logger is:

Log4j.rootlogger=[priority],appendername,appendername,...-

The syntax for configuring a custom logger component is:

Log4j.logger.loggername=[priority],appendername,appendername,...-

Log4j.rootlogger=info,stdout, R

This sentence is the output of the log information of level info to stdout and R, the definition of stdout and r in the following code, can be arbitrarily named.

Log level can be divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, if configured off will not play any information.

By default, the additive flag of logger is set to true, indicating that logger, who is not assigned a level, inherits all Appenders from his nearest parent logger. This option can be reset to indicate that the child logger will no longer inherit the appenders of the parent logger.

log4j.logger.mylogger=warn-

A logger component has been customized with a name of MyLogger and a log level of warn.

2. Configure the output destination Appender

Appender's task is to send the layout formatted output to the specified destination. Each appender is associated with a layout, and the task of layout is to format the user's logging request.

Log4j.appender.stdout=org.apache.log4j.consoleappender

This sentence defines the type of output destination named stdout, which can be

Org.apache.log4j.ConsoleAppender (console),

Org.apache.log4j.FileAppender (file),

Org.apache.log4j.DailyRollingFileAppender (generates 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)

Various types of Appender have specific configuration options, depending on the example at the end of this article, or viewing the official documentation.

3. Specify layout type

Log4j.appender.stdout.layout=org.apache.log4j.patternlayout

This sentence is the type of layout that defines the output named StdOut, which can be

Org.apache.log4j.HTMLLayout (Layout in HTML table Form),

Org.apache.log4j.PatternLayout (flexibility to specify layout mode),

Org.apache.log4j.SimpleLayout (contains the level of log information and the information string),

Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, etc.) of the log

4. Specific format

LOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=[QC]%p [%t]%c.%m (%l) | %m%n

If you use the pattern layout to specify the exact format of the printed information Conversionpattern, print the parameters as follows:

l [QC] is the beginning of the log information and can be any character, such as a project abbreviation.

L%p: Output log information priority, i.e. Debug,info,warn,error,fatal,

L%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

L%r: The number of milliseconds to output the log information from the application boot to output

L%c: Output log information belongs to the class, which is usually the full name of the class

L%t: Output The name of the thread that generated the log event

L%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)

L%x: The NDC (nested diagnostic environment) associated with the output and current line threads, especially for multi-client multithreaded applications such as Java Servlets.

L percent: outputs a "%" character

L%F: The name of the file where the output log message was generated

L%l: line number in the output code

L%M: Output The message specified in the code, resulting in the log specific information

L%n: Output a carriage return newline character, Windows platform is "/r/n", UNIX Platform for "/n" output log information line wrapping can be used to control its minimum width, maximum width, and text alignment by adding modifiers between% and pattern characters. 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.

5. Inheritance Relationship

LOG4J provides a root Logger, which is the "ancestor" of all Logger components, which is always present and cannot be retrieved or referenced by name, and is obtained through the Logger.getrootlogger () method.

Logger components with inheritance relationships can be conveniently configured in the configuration file, usually in the symbol "." The components that follow will become in the symbol "." The child class of the preceding logger component. For example:-

log4j.apache.mylogger=warn-

log4j.apache.mylogger.mysonlogger=,file-

In the above code, Mysonlogger is the subclass logger component of MyLogger.

6. Specify the log level in the package unit

Log4j.logger.com.neareast =debug

Log4j.logger.org.apache.struts=warn

Specifies that all classes under the Com.neareast package are rated as Debug.

Specifies that all classes under the Struts package are rated warn.

7. Basic Use Method

Usually there are two ways to use it:

1. Use Org.apache.commons.logging.Log class:

For example, private final log log = Logfactory.getlog (GetClass ());

2, direct use log4j of the logger class:

Obtained Rootlogger:logger Rootlogger=logger.getrootlogger ();-

Get Custom Logger:logger MyLogger =logger.getlogger ("Log4j.logger.myLogger");-

Logger is recognized by the name of a string class, root logger (root logger) is the ancestor of all logger, it has the following properties:1) it always exists;2) it cannot be obtained by name.

Public Staticlogger Logger.getlogger (Class clazz) is equivalent to calling Logger.getlogger (Clazz.getname ()), This method is considered to be the most sensible method of naming logger known at present.

The difference between the two methods:

Logfactory from common-logging bag. If using Logfactory.getlog:

Pros: You can replace log4j with any logger that implements the universal log interface, and the program is unaffected.

Disadvantage: Need one more common-logging package, this is barely a disadvantage.

Logger from Log4j's own bag. If using Logger.getlogger:

Pros: You only need a log4j jar package.

Cons: You can only use log4j as a logger, because log4j has been hardcoded into your system.

Apache's common-logging package is a universal log interface that allows you to add system flexibility by specifying which log system to use through its configuration file, Commons-logging.properties.

Other:

To maximize system performance and reduce unnecessary performance losses, use a similar decision to avoid hidden performance losses when a level of logging is turned off (even if the output log is not required, the parameter handling of a large number of debug statements also requires a considerable amount of computation):

1 if (logger.isdebugenabled () {  2     logger.debug ("Entry number:" + i + "is" +string.valueof ( Entry[i]));   3 }  

To write exception information to the log, using the E.getmessage () method does not get the correct exception stack. To output a complete exception stack, you can define a Gettrace method and then use Logger.debug (Gettrace (e)) to record the log; The Gettrace method is defined as follows:

1  Public String gettrace (Throwable t) {  2     new  StringWriter ();   3     New PrintWriter (StringWriter);   4     T.printstacktrace (writer);   5     StringBuffer buffer= stringwriter.getbuffer ();   6     return buffer.tostring ();   7 }  
8. Sample configuration file
1Log4j.rootlogger=Debug,console,database,file,rolling_file2#log4j. logger.cn.com.cnpc.backgroundserver.component.messagecomponent=Debug,console,file,rolling_file3#children-logger whether to use Rootlogger configuration4Log4j.additivity.org.apache=false  5   6 # Apply to console7log4j.appender.console=Org.apache.log4j.ConsoleAppender8log4j.appender.console.target=System.out9Log4j.appender.console.encoding=utf-8Tenlog4j.appender.console.layout=Org.apache.log4j.PatternLayout OneLog4j.appender.console.layout.conversionpattern=[%-5p]%l-%m%N A    - #应用于文件 -log4j.appender.file=Org.apache.log4j.FileAppender thelog4j.appender.file.file=e:/work/logs/OfflineMap.log -Log4j.appender.file.append=false   -Log4j.appender.file.encoding=utf-8 -log4j.appender.file.layout=Org.apache.log4j.PatternLayout +log4j.appender.file.layout.conversionpattern=%d-%-4r [%t]%-5p%l%x-%m%N -    + # Apply to file rollback Alog4j.appender.rolling_file=Org.apache.log4j.RollingFileAppender atLog4j.appender.ROLLING_FILE. file=e:/work/logs/Offlinemap.r.log -Log4j.appender.ROLLING_FILE. Threshold=INFO -Log4j.appender.ROLLING_FILE. Append=true   -Log4j.appender.ROLLING_FILE. Encoding=utf-8 -Log4j.appender.ROLLING_FILE. Maxfilesize=10240KB -Log4j.appender.ROLLING_FILE. maxbackupindex=10 inlog4j.appender.rolling_file.layout=Org.apache.log4j.PatternLayout -Log4j.appender.rolling_file.layout.conversionpattern=[framework]%d-%c-%-4r[%t]%-5p%c%x-%m%N to    + # Create a new log every day -log4j.appender.a1=Org.apache.log4j.DailyRollingFileAppender thelog4j.appender.a1.file=c:/log4j/Log *log4j.appender.a1.encoding=GBK $Log4j.appender.a1.threshold=DEBUGPanax NotoginsengLog4j.appender.a1.datepattern= '. ' yyyy-mm-DD -log4j.appender.a1.layout=Org.apache.log4j.PatternLayout theLog4j.appender.a1.layout.conversionpattern=%d{absolute}%5p%c{1}:%l:%m%N +    A # for Databases theLog4j.appender.database=Org.apache.log4j.jdbc.JDBCAppender +log4j.appender.database.url=jdbc:oracle:thin:@90.0.12.20:1521: ORCL -Log4j.appender.database.driver=Oracle.jdbc.driver.OracleDriver $Log4j.appender.database.user=Nation $Log4j.appender.database.password=1 -Log4j.appender.console.threshold=WARN -Log4j.appender.database.sql=insert into log4j (Stamp,thread,infolevel,class, messages) VALUES ('%d{yyyy-mm-dd HH:mm:ss} ', '%t ', '%p ', '%l ', '%m ')   the# INSERT into log4j (Message) VALUES (' [Framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n ')   -# Write to table in database log4j message field, content%d (date)%c: Log information location (class name)%p: Log information level%m: generated log details%N: Output log information line wrappingWuyilog4j.appender.database.layout=Org.apache.log4j.PatternLayout theLog4j.appender.database.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%N -    Wu #自定义Appender -log4j.appender.im =Net.cybercorlin.util.logger.appender.IMAppender AboutLog4j.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 ALog4j.appender.im.layout.ConversionPattern =[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%N +    the #应用于socket -log4j.appender.socket=Org.apache.log4j.RollingFileAppender $log4j.appender.socket.remotehost=localhost thelog4j.appender.socket.port=5001 thelog4j.appender.socket.locationinfo=true   thelog4j.appender.socket.layout=Org.apache.log4j.PatternLayout thelog4j.appender.socket.layout.conversionpattern=[start]%d{date}[date]%n%p[priority]%n%x[ndc]%n%t[thread]%n%c[ category]%n%m[message]%n%N -    in#LogFactor 5Appender theLog4j.appender.lf5_appender=Org.apache.log4j.lf5.LF5Appender theLog4j.appender.LF5_APPENDER. maxnumberofrecords=2000 Aboutlog4j.appender.lf5_appender.layout=Org.apache.log4j.PatternLayout theLog4j.appender.LF5_APPENDER.layout.ConversionPattern =[framework]%d-%c-%-4r[%t]%-5p%c%x-%m%N the    the #发送日志给邮件 +Log4j.appender.mail=Org.apache.log4j.net.SMTPAppender -Log4j.appender.mail.threshold=FATAL thelog4j.appender.mail.buffersize=10BayiLog4j.appender.mail.from=[email protected] thelog4j.appender.mail.smtphost=www.wusetu.com thelog4j.appender.mail.subject=log4j Message -log4j.appender.mail.to=[email protected] -log4j.appender.mail.layout=Org.apache.log4j.PatternLayout theLog4j.appender.mail.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-%m%n

"Turn-Organize" log4j simple explanation, configuration

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.