LOG4J Basic explanation and example Daquan

Source: Internet
Author: User
Tags log log

LOG4J can be configured by using a configuration file.
The configuration steps are as follows:

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.
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 (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)
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 defines the type of layout for 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 level and information strings for log information)
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:

[QC] is the beginning of the log information and can be any character, such as a project abbreviation.
%p: Output log information priority, Debug,info,warn,error,fatal, etc.
%d: the date or time of the output log point in time, the default format is ISO8601, or the format can be specified thereafter, such as:%d{yyy MMM DD hh:mm : ss,sss}, output similar to: October 18, 2002 22:10:28,921
%r: Output from app startup to output the log information in milliseconds
% c: The class to which the output log information belongs, usually the full name of the class
%t: Output the name of the thread that generated the log event
% L: The occurrence of the output log event, equivalent 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 the current line threads, especially for multi-client multithreaded applications like Java Servlets.
%: Output A "%" character
% F: The file name where the output log message was generated
% L: line number in the output code
%M: The message specified in the output code, resulting in the log specific information
%n: Output a carriage return newline character, the Windows platform is "/ r/n ", UNIX Platform for"/n "Output log information wrapping allows you to control its minimum width, maximum width, and text alignment by adding modifiers between% and pattern characters. For example:
1)%20c: Specifies 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: Specifies the name of the output category, the minimum width is 20, if the category name is less than 20, the "-" number specifies left-justified.
3)%.30c: Specifies 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-align, and if its name is longer than 30 characters, it is truncated from a character that is farther away from the left.

5. Succession relations
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.

In addition, to maximize the performance of the system, reduce unnecessary performance loss, using a similar to the following judgment can be closed at a certain level of the log to avoid the hidden performance loss (even if the output log is not required, a large number of debug statements such as parameter processing also need to consume a considerable amount of computation):

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

8. Configuration File Example

log4j.rootlogger=debug,console,database,file,rolling_filelog4j.addivity.org.apache=true# Apply to console log4j.appender.console=org.apache.log4j.consoleappenderlog4j.appender.console.threshold= infolog4j.appender.console.target=system.outlog4j.appender.console.encoding=gbklog4j.appender.console.layout= Org.apache.log4j.patternlayoutlog4j.appender.console.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c% X-%m%n# for database log4j.appender.database=org.apache.log4j.jdbc.jdbcappenderlog4j.appender.database.url=jdbc:oracle: Thin:@90.0.12.20:1521:orcllog4j.appender.database.driver= oracle.jdbc.driver.oracledriverlog4j.appender.database.user=nationlog4j.appender.database.password= 1log4j.appender.console.threshold=warnlog4j.appender.database.sql=insert into log4j (stamp,thread,infolevel,class , messages) VALUES ('%d{yyyy-mm-dd HH:mm:ss} ', '%t ', '%p ', '%l ', '%m ') # INSERT into log4j (Message) VALUES (' [Framework]%d -%c-%-4r [%t]%-5p%c%x-%m%n ') # Write to the table in the database in the LOG4J message field, content%d (date)%c: Log information location (class name)%p: LogInformation level%m: Log specific information generated%n: output log message line wrapping log4j.appender.database.layout= Org.apache.log4j.patternlayoutlog4j.appender.database.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c %x-%m%n# apply to file log4j.appender.file=org.apache.log4j.fileappenderlog4j.appender.file.file=c:/log4j/ file.loglog4j.appender.file.append=falselog4j.appender.file.encoding=gbklog4j.appender.file.layout= Org.apache.log4j.patternlayoutlog4j.appender.file.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-% m%n# applies to file rollback log4j.appender.rolling_file=org.apache.log4j.rollingfileappenderlog4j.appender.rolling_file. Threshold=errorlog4j.appender.rolling_file. File=rolling.loglog4j.appender.rolling_file. Append=truelog4j.appender.rolling_file. Encoding=gbklog4j.appender.rolling_file. Maxfilesize=10kblog4j.appender.rolling_file. Maxbackupindex=1log4j.appender.rolling_file.layout=org.apache.log4j.patternlayoutlog4j.appender.rolling_ File.layout.conversionpattern=[framework]%d-%c-%-4r[%t]%-5p%c%x-%m%n# new log per day4j.appender.a1=org.apache.log4j.dailyrollingfileappenderlog4j.appender.a1.file=c:/log4j/ Loglog4j.appender.a1.encoding=gbklog4j.appender.a1.threshold=debuglog4j.appender.a1.datepattern= '. ' yyyy-mm-ddlog4j.appender.a1.layout=org.apache.log4j.patternlayoutlog4j.appender.a1.layout.conversionpattern=%d {ABSOLUTE}%5p%c{1}:%l:%m%n# Custom Appenderlog4j.appender.im = Net.cybercorlin.util.logger.appender.IMAppenderlog4j.appender.im.host = Mail.cybercorlin.netlog4j.appender.im.username = Usernamelog4j.appender.im.password = Passwordlog4j.appender.im.recipient = [email protected]log4j.appender.im.layout= Org.apache.log4j.PatternLayoutlog4j.appender.im.layout.ConversionPattern =[framework]%d-%c-%-4r [%t]%-5p%c%x-%m% n# applied to socketlog4j.appender.socket=org.apache.log4j.rollingfileappenderlog4j.appender.socket.remotehost= localhostlog4j.appender.socket.port=5001log4j.appender.socket.locationinfo=truelog4j.appender.socket.layout= Org.apache.log4j.PatternLayoutlog4j.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# LogFactor 5 Appenderlog4j.appender.lf5_appender=org.apache.log4j.lf5.lf5appenderlog4j.appender.lf5_appender. Maxnumberofrecords=2000log4j.appender.lf5_appender.layout=org.apache.log4j.patternlayoutlog4j.appender.lf5_ APPENDER.layout.ConversionPattern =[framework]%d-%c-%-4r[%t]%-5p%c%x-%m%n# send log to Message Log4j.appender.mail=org.apache .log4j.net.smtpappenderlog4j.appender.mail.threshold=fatallog4j.appender.mail.buffersize=10[email  Protected]log4j.appender.mail.smtphost=www.wusetu.comlog4j.appender.mail.subject=log4j Message[email  protected]log4j.appender.mail.layout= Org.apache.log4j.patternlayoutlog4j.appender.mail.layout.conversionpattern=[framework]%d-%c-%-4r [%t]%-5p%c%x-% m%n

Transferred from: http://www.open-open.com/lib/view/open1337754346355.html

LOG4J Basic Explanation and Example Daquan (GO)

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.