Java log processing Component Log4j--log4j.xml configuration detailed

Source: Internet
Author: User
Tags system log truncated log4j

<!--log4j System log-->
Note: this information is searched through the network and then sorted into

First of all, to explain the parameters of the configuration file, so that the configuration can be reasonable.

Description of parameter meaning:

Configure Root Logger

Its syntax is:
    Log4j.rootlogger = [level], appenderName1, appenderName2, ...
Level: Is the priority of the logging, divided into
the levels you define by off, FATAL, ERROR, WARN, INFO, DEBUG, all, or a person. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG. By the level defined here, you can control the switch to log information at the appropriate level in your application. For example, if the info level is defined here, all debug-level log information in the application will not be printed.
appendername: Is to specify where the log information is exported. You can specify multiple output destinations at the same time.
 		For example: LOG4J.ROOTLOGGER=INFO,A1,B2,C3

Type of output level

Off, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, all
 off log information is turned off for the highest level FATAL error is critical for fatal	event errors that may cause application abort
 Mainly is the error of the program
 WARN for general warning, such as session lost
 info for general to display information, such as login log out
 debug for program debugging information
 TRACE is more granular than debug event information
 all to lowest level, all levels of log will open


Configure log information output destinations

Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
 1.org.apache.log4j.consoleappender (console)
 2.org.apache.log4j.fileappender (file)
 3.org.apache.log4j.dailyrollingfileappender (produces one log file per day)
 4. Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size)
 5. Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)


Configure the format of log information

Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
 1. Org.apache.log4j.HTMLLayout (layout in HTML table),
 2.org.apache.log4j.patternlayout (you can specify layout patterns flexibly),
 3. Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
 4.org.apache.log4j.ttcclayout (contains information about the time, thread, category, and so on that the log was generated)


Console Options
Threshold=debug: Specifies the lowest level of output for log messages.
 immediateflush=true: The default value is true, meaning that all messages will be immediately exported.
 Target=system.err: By default: System.out, specify output console

 fileappender Options
 THRESHOLD=DEBUF: Specifies the lowest level of output for log messages.
 immediateflush=true: The default value is true, meaning that all messages will be immediately exported.
 file=mylog.txt: Specifies the message output to the Mylog.txt file.
 Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.

 rollingfileappender Options
 Threshold=debug: Specifies the lowest level of output for log messages.
 immediateflush=true: The default value is true, meaning that all messages will be immediately exported.
 file=mylog.txt: Specifies the message output to the Mylog.txt file.
 Append=false: The default value is True, the message is incremented to the specified file, and false refers to overwriting the specified file contents with the message.
 maxfilesize=100kb: The suffix can be kb, MB, or GB. When the log file reaches that size, it scrolls automatically, moving the original content to the Mylog.log.1 file.
 maxbackupindex=2: Specifies the maximum number of scrolling files that can be produced.
 log4j.appender.a1.layout.conversionpattern=%-4r%-5p%d{yyyy-mm-dd HH:mm:ssS}%c%m%n


The meanings represented by several symbols in the log Information format:

  -x: X Information output left-aligned;
  %p: Output log information priority, that is, Debug,info,warn,error,fatal,
  %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 is similar: October 18, 2002 22:10:28,921
  %r: Output from the application boot to the output of this log information consumption of milliseconds
  %c: output log information belongs to the class, Usually the full name of the class in which the
  %t: output produces the thread name of the log event
  %l: The location of the output log event, which is equivalent to the combination of%c.%m (%f:%l), including the class name, the thread that occurred, and the number of lines in the code. For example: Testlog4.main (testlog4.java:10)
  %x: The NDC (nested diagnostics environment) associated with the current line threads relative, especially in multiple client multi-threaded applications such as Java Servlets.
  percent%: output a "%" character
  %F: The name of the file where the output log message is generated
  %l: line number in the output code
  %m: The message specified in the output code, the log specific information generated
  %n: output a carriage return line break, The Windows platform is "/r/n", and the UNIX platform is "/n" output log message wrapping
  can 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, and if the category name is less than 20, the default is right-aligned.
  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-aligned.
  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 characters truncated, but less than 30 words will not have spaces.
  4)%20.30c: If the name of the category is less than 20, the space is filled and right-aligned, and if its name is longer than 30 characters, it is truncated from the character that is farther from the left.

The Log4j.xml configuration is as follows, Log4j.xml is stored in the Web-inf directory:

<?xml version= "1.0" encoding= "GBK"?> <! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" > <log4j:configuration xmlns:log4j= "http://jakarta.apache.org/" log4j/"> <!--output log to console Consoleappender--> <appender name=" console "class=" Org.apache.lo G4j. Consoleappender "> <param name=" Threshold "value=" info "></param> <layout class=" org.apache.log4j. Ttcclayout "> <param name=" Conversionpattern "value=" Ttcclayout "></param> </layout> </a ppender> <!--output log to file every day a file--> <appender name= "Dailyrollingfile" class= Ingfileappender "> <param name=" Threshold "value=" info "></param> <param name=" Immediateflush "Val  Ue= "true" ></param> <param name= "File" value= "C:/logs/dailyrollingfile.log" ></param> <param Name= "Datepattern" value= "'. ' Yyyy-mm-dd '. Log ' "></param> <layout class=" Org.apachE.log4j.patternlayout "> <param name=" Conversionpattern "value=" [%d{yyyy-mm-dd hh:mm:ss\}%-5p] [%t] {%c:%L}-%m% N "></param> </layout> </appender> <!--output log to file size to reach a specified size when a new file is generated--> ; Appender name= "Railyfile" class= "Org.apache.log4j.RollingFileAppender" > <param name= "File" value= "c:/logs/ RailyFile.log "></param> <param name=" Immediateflush "value=" true "/>" <param "name=" Threshold "Valu E= "Info" ></param> <param name= "Append" value= "true" ></param> <param "Name=" Val Ue= "30KB" ></param> <param name= "Maxbackupindex" value= "></param> <layout class=" Org.ap Ache.log4j.PatternLayout "> <param name=" Conversionpattern "value=" [%d{yyyy-mm-dd hh:mm:ss\}%-5p] [%t] {%c:%l}-
  		%m%n "></param> </layout> </appender> <!--output log to file--> <appender name=" File " Class= "Org.apache.log4J.fileappender "> <param name=" File "value=" C:/logs/file.log "></param> <param name=" Threshold "va Lue= "Info" ></param> <layout class= "Org.apache.log4j.PatternLayout" > <param name= "Conversionpatt"

	Ern "Value=" [%d{yyyy-mm-dd hh:mm:ss\}%-5p] [%t] {%c:%l}-%m%n "></param> </layout> </appender>
	    The <!--defines the global log output level, but the specific output level priority configured in the output destination configuration is higher than the globally defined priority.     
		If the <param name= "Threshold" value= "info" &GT;&LT;/PARAM&GT is defined in Railyfile, then the information above the info level will be exported--> <root> <priority value= "Debug"/> <appender-ref ref= "console"/> <appender-ref ref= "dailyrolling"     	

File "/> <appender-ref ref=" railyfile/> <appender-ref ref= "file"/> </root>  </log4j:configuration>


Add Log4j.xml configuration to Web.xml

	<!--log4j System log-->
	<context-param> 
	  	<param-name>log4jConfigLocation</param-name> 
	 	<param-value>/WEB-INF/log4j.xml</param-value> 
	</context-param> 
	<listener> 
	  	<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> 
	</ Listener>


Simple encapsulation of the logger:

Basicconfigurator.configure (); Read Log4j.xml first, and then read log4j.properties if it does not exist.

public class Log4jutil {
	private static final String configfile = "Log4j.xml";
	
	static{
		basicconfigurator.configure ();
	}
	
	Public Log4jutil () {
		super ();
	}
	
	public static String Getconfigfile () {return
		configfile;
	}
	
	public static Logger GetLogger (Class clazz) {return
		Logger.getlogger (clazz);
	}
	
	public static Logger GetLogger (String strclass) {return
		Logger.getlogger (strclass);
	}
	
	public static Logger GetLogger (String strclass,loggerfactory loggerfactory) {return
		Logger.getlogger (strclass, loggerfactory);
	}
	
	


The last thing you need to do is call in your code, in the following format:

public class Hellolog4j {

	private static Logger Logger = Logger.getlogger (hellolog4j.class);

	Public  String GetURL () {
		logger.info ()-GetURL () ... ");
		return null;
	}
}

So the log4j is configured successfully.




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.