LOG4J extended Use--Log recorder Logger

Source: Internet
Author: User
Tags getmessage log4j


OK, now we carefully study the configuration of the next logger, the related configuration extension.

Log4j has three main components: loggers (recorder), appenders (output source), and layouts (layout). Among them, logger is responsible for logging, Appender responsible for the output to where, layout is responsible for what format output, output which additional information. The combination of these three components makes it easy to record the type and level of information and to control the style and location of the log output at run time.

log4j Three core concepts Common class Logger is responsible for most of the operations that log records are processed.
The public interface Appender is responsible for controlling the output of the log records.
Public abstract class Layout is responsible for formatting Appender output


The logger logger is the core component of log processing. Now let's take this component seriously. Logger is the logger in Java code, for example:

public static Logger log = Logger.getlogger (Log4jtest.class);
Logger has a name, and its name is the parameter of the Logger.getlogger () method. If the argument is the class, log4j will go to the name of the logger, such as org.linkinpark.commons.logtest.Log4jTest.

The loggers component is divided into five levels in this system:Trace→debug→info→warning→error→fatal→off. It is important to keep in mind that the level of the grade is high and the level of automatic shielding is low.

Here log4j has a rule: assuming the loggers level is P, if a level Q in loggers is higher than p, it can be activated or shielded. If you define a level of info, then the error and warn log can be displayed and the debug information below him is not displayed.

Note the following points:

1,logger is a single state mode, and logger with the same name will only have one instance. If you build a logger,log4j with the same name, the previous logger instance is returned.

2, in general, the name of the class is logger. Logger's name is similar to the package in Java, case sensitive, separated by dots and has an inheritance relationship. Logger properties are configured by name in Log4j.properties.

3, when the logger instance is named, there is no limit, you can take any name you are interested in. In general, it is recommended to name the logger instance where the class is located, which is a more effective logger naming method at the moment. This allows each class to establish its own log information for easy management.

4,LOG4J has a root logger rootlogger, which is the parent class for all logger.

The configuration of Logger is in log.properties configuration log4j.properties, Log4j.logger is configured with a logger,log4j.appender after Appender.

Log4j.logger.org.linkinpark.commons.logtest.log4jtest=info,console
If a logger is not configured, use its father configuration until it is found. Under normal circumstances, only need to configure the root logger Rootlogger, all logger will follow the Rootlogger configuration.

Rootlogger ConfigurationThe root logger Rootlogger can be configured directly with Log4j.rootlogger. Rootlogger is the father of all loggers, and any logger can inherit the Rootlogger configuration, as follows:
#log4j. Rootlogger=debug,console,file
#log4j. Logger.org.linkinpark.commons.logtest.log4jtest=info
Log4j.rootlogger=info,console
  
#输出到控制台   
log4j.appender.console=org.apache.log4j.consoleappender  
# Set output style   
log4j.appender.console.layout=org.apache.log4j.patternlayout 
#日志输出信息格式为
Note: If you want to make a special output to a logger, just configure the logger to OK, covering the father's configuration can be. When overridden, you can configure only levels, outputs, or 2 of them.

OK, now let's give an example.

For example, I now have the following requirements, general log printing I follow a specific configuration is enough, but there is a special class, I need to make a special configuration so how to do it.

1, write a good 2 Java source code, output log

2, the main is to write a good log4j.properties file. It is enough to define the Rootlogger and then the subclass to reconfigure the overlay rootlogger. But there is a problem is that if subclasses redefine Appender, still inherit Rootlogger configuration, that is to say, 2 log output, I faint.

Therefore, it is recommended that the control of the subclass overrides overwrite the Rootlogger configuration, and only the log level is rewritten. OK, others don't move. OK, now post the code:

package org.linkinpark.commons.logtest;

Import Org.apache.log4j.Logger; /** * Create Author: Linkinpark * @ Creation Date: February 23, 2016 * @ Feature Description: This class uses log4j rootlogger default output */public class Log4jtest {public STA

	Tic Logger log = Logger.getlogger (Log4jtest.class); /** * @ Creation Date: February 22, 2016 * @ Related parameters: * @ Function Description: Define an output log method * <p> * Trace→debug→info→warn→error→fatal→off * level
	 In turn, higher level levels will mask lower levels.
		* </p>/public static void Logtest () {System.out.println ("======= here is the log output of the Rootlogger class = = = =");
		if (log.isdebugenabled ()) {Log.debug ("debug-level log Output");
		} log.trace ("Trace-level log output");
		Log.info ("Log output at info level");
		Log.warn ("Log output at warn level");
		Log.error ("Error-level log output");
		Log.fatal ("Log output at fatal level");
		try {System.out.println (9/0);
		catch (RuntimeException e) {log.error (E.getmessage ());
	} public static void Main (string[] args) {logtest (); }

}
package org.linkinpark.commons.logtest;

Import Org.apache.log4j.Logger; /** * Create Author: Linkinpark * @ creation time: February 23, 2016 * @ Feature Description: This class reconfiguration to override Rootlogger Log level/public class Log4jtest1 {public

	static Logger log = Logger.getlogger (Log4jtest1.class); /** * @ Creation Date: February 22, 2016 * @ Related parameters: * @ Function Description: Define an output log method * <p> * Trace→debug→info→warn→error→fatal→off * level
	 In turn, higher level levels will mask lower levels.
		* </p>/public static void Logtest () {System.out.println ("======= here is the log output of a particular class = = = =");
		Log.info ("Log output at info level");
		Log.warn ("Log output at warn level");
		Log.error ("Error-level log output");
		Log.fatal ("Log output at fatal level");
		Try {throw new NullPointerException ("Throw an exception manually");
		catch (RuntimeException e) {log.error (E.getmessage ());
		} public static void Main (string[] args) {logtest ();
	Log4jtest.logtest (); }

}
# can be set level: Trace→debug→info→warning→error→fatal→off # High level levels block low-level levels. # debug: Show debug, info, error # Info: Show info, error #log4j. Rootlogger=debug,console,file log4j.logger.org.linkinpark.com Mons.logtest.log4jtest1=error Log4j.rootlogger=info,console # This is Rootlogger configuration, subclass default inheritance, but subclass overrides the following configuration =rootlogger+ its own configuration, I'm dizzy #输出到控制台 log4j.appender.console=org.apache.log4j.consoleappender #设置输出样式 Log4j.appender.console.layout=org.apach. E.log4j.patternlayout #日志输出信息格式为 Log4j.appender.console.layout.conversionpattern=[%-d{yyyy-mm-dd HH:mm:ss}]-[%t-% 5p]-[%c-%m (%l)]:%m%n #输出到文件 (this defaults to append) #log4j. Appender.file=org.apache.log4j.fileappender # Log4j.appender.file.file=f:/linkinpark/logs/log4j.log #样式为TTCCLayout #log4j. appender.file.layout= Org.apache.log4j.TTCCLayout #自定义样式 #%c output belongs to the class, usually the full name of the class #%c output logger the name of the class, typically the full name of the class in which it is located #%d the date or time of the output log point-in-time, the default format is ISO
8601, you can also specify the format later, such as:%d{yyy MMM dd HH:mm:ss, sss},%d{absolute},%d{date} #%f the class name of the class, only the class name. #%l the number of rows in which the output statement is located, including the class name + method name + filename + number of rows #%l the number of rows in which the output statement is located,Outputs only the messages specified in the output code of the digital #%m, such as the message #%m output method name #%p output log level in log, that is, Debug,info,warn,error,fatal #%r Output from the application boot to the output of this log information the number of milliseconds #%t output produces the Log event thread name #%n output a carriage return line break, Windows platform for "/r/n", UNIX Platform for "/n" #%% to output percent "%" # Log4j.appender.linkin.layout.conversionpattern=%n[%l%d{yy/mm/dd Hh:mm:ss:sss}][%c-%m]%M # Log4j.appender.linkin.layout.conversionpattern=%-d{yyyy-mm-dd hh:mm:ss}[%c]-[%p]%m%n #
 Log4j.appender.Linkin.layout.ConversionPattern =%d{absolute}%5p%t%c{2}:%l-%m%n

OK, now let's look at the console output, no problem.

======= here is the log output of a particular class = = = = = = = = = [2016-02-23 00:23:54]-[main-error]-[ Org.linkinpark.commons.logtest.log4jtest1-logtest]: Error-level log output [2016-02-23 00:23:54]-[main-fatal]-[ Org.linkinpark.commons.logtest.log4jtest1-logtest]: Log output at fatal level [2016-02-23 00:23:54]-[main-error]-[ Org.linkinpark.commons.logtest.log4jtest1-logtest (32)]: artificially thrown an exception ======= here is the Rootlogger class's log output = = = = = = = (2016-02-23 00:23:54]-[main-info]-[org.linkinpark.commons.logtest.log4jtest-logtest]: Log output at INFO level [2016-02-23 00:23:54]-[ Main-warn]-[org.linkinpark.commons.logtest.log4jtest-logtest]: Log output at WARN level [2016-02-23 00:23:54]-[main-error] -[org.linkinpark.commons.logtest.log4jtest-logtest]: Error level log output [2016-02-23 00:23:54]-[main-fatal]-[ Org.linkinpark.commons.logtest.log4jtest-logtest: Log output at fatal level [2016-02-23 00:23:54]-[main-error]-[ Org.linkinpark.commons.logtest.log4jtest-logtest (Panax)]:/by Zero 


The category category configuration Logger also has a category (category) concept, Rongguo sets the category to set all the logger under the category. Category is similar to Java package, and the effect is equivalent to the logger name. Here's a good example:

OK, we copy the previous log4jtest to a new package Logtest1, 2 Java code unchanged, and then set the configuration file to control different log levels, to see the effect.



# can be set level: Trace→debug→info→warning→error→fatal→off # High level levels block low-level levels.
# debug: Show debug, info, error # Info: Show info, error #log4j. Rootlogger=debug,console,file #子类重新定义日志级别, Logger's name is the class name of the log class #log4j. Logger.org.linkinpark.commons.logtest.log4jtest1=error #子类重新定义日志级别, category's name is the package name of the log class,
Category can be interpreted as a Java package. Log4j.category.org.linkinpark.commons.logtest1=error Log4j.rootlogger=debug,console # Below is the RootLogger configuration, subclass default inheritance, But subclasses override the following configuration =rootlogger+ own configuration, I faint #输出到控制台 log4j.appender.console=org.apache.log4j.consoleappender #设置输出样式 log4j.append Er.console.layout=org.apache.log4j.patternlayout #日志输出信息格式为 log4j.appender.console.layout.conversionpattern=[%-d {YYYY-MM-DD HH:mm:ss}] -[%t-%5p]-[%c-%m (%l)]:%m%n #输出到文件 (this defaults to append) #log4j. Appender.file=org.apache.log4j.fileappender # Log4j.appender.file.file=f:/linkinpark/logs/log4j.log #样式为TTCCLayout #log4j. appender.file.layout= Org.apache.log4j.TTCCLayout #自定义样式 #%c output belongs to the class, usually the full name of the class #%c output logger the name of the class, usually the full name of the class where the output log point of time or the date, the default format is ISO8601, or the format can be specified later, for example:%d{yyy MMM dd HH:mm:ss, sss},%d{absolute},%d{date} #%f the class name of the class in which the output is located, only the class name. #%l the number of rows in which the output statement is located, including the class name + method name + file name + number of rows #%l output statement, output only the number specified in the output code, such as the message in log #%m output method name #%p output log level, that is, debug,	Info,warn,error,fatal #%r Output The number of milliseconds it takes to output the log information #%t output the thread name that generated the log event #%n output a carriage return line feed, Windows platform "/r/n", and UNIX platform "n" #%% Used to output percent "%" #log4j. Appender.linkin.layout.conversionpattern=%n[%l%d{yy/mm/dd hh:mm:ss:sss}][%c-%m]%M # Log4j.appender.linkin.layout.conversionpattern=%-d{yyyy-mm-dd hh:mm:ss}[%c]-[%p]%m%n #
 Log4j.appender.Linkin.layout.ConversionPattern =%d{absolute}%5p%t%c{2}:%l-%m%n
OK, now let's look at the console output: No problem, successfully output the log below the specific package we defined ourselves, and follow our own configured log level.

======= Here is the log output of the class below the specific package = = = = = = = = = = = 00:39:56]-[main-error]-[ Org.linkinpark.commons.logtest1.log4jtest1-logtest: Log output at the error level [2016-02-23 00:39:56]-[main-fatal]-[ Org.linkinpark.commons.logtest1.log4jtest1-logtest: Log output at fatal level [2016-02-23 00:39:56]-[main-error]-[ Org.linkinpark.commons.logtest1.log4jtest1-logtest (38)]: artificially thrown an exception ======= here is the Rootlogger class's log output = = = = = = = (2016-02-23 00:39:56]-[main-debug]-[org.linkinpark.commons.logtest.log4jtest-logtest]: DEBUG-level log output [2016-02-23 00:39:56] -[main-info]-[org.linkinpark.commons.logtest.log4jtest-logtest]: Log output at INFO level [2016-02-23 00:39:56]-[main-warn ]-[org.linkinpark.commons.logtest.log4jtest-logtest: Log output at warn level [2016-02-23 00:39:56]-[main-error]-[ Org.linkinpark.commons.logtest.log4jtest-logtest): Error-level log output [2016-02-23 00:39:56]-[main-fatal]-[ org.linkinpark.commons.logtest.log4jtest-logtest): Log output at fatal level [2016-02-23 00:39:56]-[main-error]-[ Org.linkinpark.commons.logtest.log4jtest-logtest ()]:/by ZerO
  

OK, the next article I will organize to log output component Appender.

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.