Apache log4j Notes

Source: Internet
Author: User
good coding, good architecture.

How to write a good debug log record, no doubt, Log4j,slf4j,,logback is one of the necessary choice.

The behavior of the log recorder (Logger) is hierarchical. As shown in the following table:
Can be divided into off, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, all, or the level you define. LOG4J recommends using only four levels, from high to low, respectively, for error, WARN, INFO, and DEBUG.

Generally speaking, these 4 is enough, the Internet to see someone custom log level, feel absolutely unnecessary. Others say that log4j has only 5 or 4 levels, and this is not a good idea.

The classic log4j.

#log4j. Appender.stdout=org.apache.log4j.consoleappender #log4j. appender.stdout.layout= Org.apache.log4j.PatternLayout #log4j. appender.stdout.layout.conversionpattern= (%f:%l)-%m%n Log4j.rootlogger = 
DEBUG,A1,A4 Log4j.appender.a1.threshold=debug Log4j.appender.a1=org.apache.log4j.dailyrollingfileappender Log4j.appender.a1.layout=org.apache.log4j.patternlayout #log4j. appender.a1.layout.conversionpattern=[%-5p]%d{ Yyyy-mm-dd hh:mm:ss,sss}%l%n%m%n log4j.appender.a1.layout.conversionpattern=[%-5p]%d{yyyy-MM-dd HH:mm:ss,SSS}
method:%l%m%n log4j.appender.a1.file=${webapphome}/logs/log.txt log4j.appender.a1.datepattern=yyyy-mm-dd ' txt ' Log4j.appender.a1.encoding=utf-8 #log4j. appender.a1.maxfilesize= 1000KB log4j.appender.a4=
Org.apache.log4j.FileAppender Log4j.appender.a4.encoding=utf-8 Log4j.appender.a4.file=alllog.txt
Log4j.appender.a4.append=true Log4j.appender.a4.layout=org.apache.log4j.patternlayout LOG4J.APPENDER.A4.LAYOUT.CONVERSIONPATTERN=[%-5P]%d{yyyy-mm-dd Hh:mm:ss,sss} method:%l%n%m%n
 

Configure Webhome:

If it is a Web project, it can be configured in Web.xml.

<servlet>
		<servlet-name>Log4jinit</servlet-name>
		<servlet-class> com.sinoglobal.servlets.log4jinit</servlet-class>
		<init-param>
			<param-name>log4j< /param-name>
			<param-value>WEB-INF/classes/log4j.properties</param-value>
		</ init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	< servlet-mapping>
		<servlet-name>Log4jinit</servlet-name>
		<url-pattern>/log4jinit </url-pattern>
	</servlet-mapping>
Package com.sinoglobal.servlets;

Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;

Import Org.apache.log4j.PropertyConfigurator;

Import Com.sinoglobal.cons.Const;
Import Com.sinoglobal.utils.DateUtils;


public class Log4jinit extends HttpServlet
{
	private static final long	serialversionuid	=- 3297990648398759356L;
	
	@Override public
	void Init () throws Servletexception
	{
		String prefix = Getservletcontext (). Getrealpath ("/");
		String test = Getservletcontext (). Getrealpath ("");
		System.setproperty ("Webapphome", test);
		String file = Getservletconfig (). Getinitparameter ("log4j");
		Const.sysstarttime=dateutils.getnowdate ("Yyyy-mm-dd HH:mm:ss.") SSS ");

		Read the log4j profile
		if (file!= null)
		{
			propertyconfigurator.configure (prefix + file) from
		the servlet parameter;}
	
}

If this is a Java project, you can configure this:

private void initlog4j () {
		String path=iconutils.root;
		System.setproperty ("Webapphome", path);
		Propertyconfigurator.configure (path + "/src/log4j.properties");
		Logger.info ("an error.") ");
	}
In Iconutils:

Package com.ui;

Import Java.awt.Color;
Import Java.awt.Toolkit;

Import Javax.swing.ImageIcon;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
/**
 * Common method for setting background pictures and system icons
 * @author LZ
 */public
class Iconutils {publicly
	final static String Root = System.getproperty ("User.dir");
	Public final static Toolkit tk = Toolkit.getdefaulttoolkit ();
	Private final static ImageIcon img = new ImageIcon (root +/resource/img/login). JPG ");
	Private final static JLabel Imglabel = new JLabel (IMG);//The background image is placed in the label public
	static void SetIcon (JFrame JF) {
		Jf.s Eticonimage (Tk.createimage (root + "/resource/img/emule.png"));
	}
	
	public static void SetBackgroundImage (JFrame JF) {
		jf.getcontentpane (). SetBackground (Color.White);
		Jf.add (Imglabel, New Integer (Integer.min_value));
		Imglabel.setbounds (0, 0, img.geticonwidth (), Img.geticonheight ());
	}


In order to prevent garbled, we have configured the log4j.appender.a4.encoding=utf-8 inside. Can effectively prevent garbled, different system file encoding is different after all.

The above configuration is one for Alllog.txt, one for a day to generate a log, generate errors, you can change the computer time, found that it will be the day before the Log.txt plus time, that is log4j.appender.a1.datepattern= Yyyy-mm-dd ' txt ' this sentence.

System.getproperty ("User.dir"); Gets the home directory of the current project.

And the more detailed record of it, here do not repeat, there are many online.

It's important to know where the conversionpattern[output format is and the log output. Log level.

You can write a DTD statement of your own:

<?xml version= "1.0" encoding= "UTF-8"?> <!--authors:chris Taylor, Ceki GULCU. --> <!--version:1.2--> <!--A configuration element consists of optional renderer Elements,appender Eleme NTS, categories and an optional root element. --> <! ELEMENT log4j:configuration (renderer*, appender*, (Category|logger) *,root?, Categoryfactory ?) > <!--the "threshold" attribute takes a level value such which all--> <!--logging statements and a level E Qual or below this value are--> <!--disabled.                                                         --> <!--Setting the "debug" enable the printing of internal log4j logging--> <!--statements. --> <!--By default, the debug attribute is ' null ', meaning that we don't D O Touch--> <!--internal log4j logging settings. The "null" value for the threshold--> <!--attribute can is misleading. The threshold field of a repository--> <!-- Cannot is set to NULL. The "null" value for the threshold attribute--> <!--simply means don t touch the threshold field, the threshold fi                                                Eld--> <!--keeps its old value. --> <!                Attlist log4j:configuration xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/" threshold (All|debug|info|warn|error|fatal|off|null) "NULL" Debug (true|false|null) "null" > <!--renderer elements allow the user to customize th                                       e Conversion of--> <!--message objects to String. --> <! ELEMENT renderer empty> <! Attlist renderer renderedclass CDATA #REQUIRED renderingclass CDATA #REQUIRED > <!--appenders must have a Nam E and a class. --> <!--appenders may contain the error handler, a layout, optional parameters--> <!--and filters. They may also reference (or include) appenders. --&gT <! ELEMENT Appender (ErrorHandler, param*, Layout, filter*, appender-ref*) > <! Attlist Appender name ID #REQUIRED class CDATA #REQUIRED > <! ELEMENT layout (param*) > <! Attlist Layout class CDATA #REQUIRED > <! ELEMENT filter (param*) > <! ATTLIST Filter Class CDATA #REQUIRED > <!--errorhandlers can of any class. They can admit any number of--> <!--parameters. --> <! ELEMENT ErrorHandler (param*, Root-ref, logger-ref*, appender-ref?) > <! Attlist ErrorHandler class CDATA #REQUIRED > <! ELEMENT root-ref empty> <! ELEMENT logger-ref empty> <! Attlist logger-ref ref IDREF #REQUIRED > <! ELEMENT param empty> <! ATTLIST param name CDATA #REQUIRED value CDATA #REQUIRED > <!--the priority class is Org.apache.log4j.Lev El By default--> <! ELEMENT priority (param*) > <! Attlist Priority class CDATA #IMPLIED value CDATA #REQUIRED > <!--The level class was org.apache.log4j.Level by default--> <! ELEMENT level (param*) > <!  Attlist Level class CDATA #IMPLIED value CDATA #REQUIRED > <!--If No level element is specified, then the Configurator must not--> <!--to the level of the named category. --> <! ELEMENT category (param*, (priority|level)?, appender-ref*) > <!  Attlist Category class CDATA #IMPLIED name CDATA #REQUIRED additivity (True|false) "true" > <!-- If no level element is specified, then the Configurator must not--> <!--to the level of the named logger. --> <! ELEMENT logger (level?,appender-ref*) > <! attlist Logger name ID #REQUIRED additivity (true|false) "true" > <! ELEMENT categoryfactory (param*) > <! Attlist categoryfactory class CDATA #REQUIRED > <! ELEMENT appender-ref empty> <! Attlist appender-ref ref IDREF #REQUIRED > <!--If No priority element is specified, thEn the Configurator must not--> <!--touch the priority of root. --> <!--The root category always exists and cannot be subclassed. --> <! ELEMENT Root (param*, (priority|level)?, appender-ref*) > <!--================================================ ====================--> <!--A Logging Event--> <!--= = ==================================================================--> <! ELEMENT log4j:eventset (log4j:event*) > <!                Attlist log4j:eventset xmlns:log4j CDATA #FIXED "http://jakarta.apache.org/log4j/" version (1.1|1.2) "1.2" Includeslocationinfo (True|false) "true" > <! ELEMENT log4j:event (Log4j:message, LOG4J:NDC, log4j:throwable, log4j:locationinfo?) > <! -The timestamp format is application dependent. --> <!  Attlist Log4j:event Logger CDATA #REQUIRED level CDATA #REQUIRED Thread   CDATA #REQUIRED timestamp CDATA #REQUIRED > <! ELEMENT log4j:message (#PCDATA) > <! ELEMENT LOG4J:NDC (#PCDATA) > <! ELEMENT log4j:throwable (#PCDATA) > <! ELEMENT Log4j:locationinfo empty> <! Attlist Log4j:locationinfo Class CDATA #REQUIRED method CDATA #REQUIRED File CDATA #REQUIRED line CDATA #REQU ired >

Write another implementation of a DTD:

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" > <log4j:configuration xmlns:log4j= ' http://jakarta.apache.org/ log4j/' > <!--output log information to console--> <appender name= "STDOUT" class= "Org.apache.log4j.ConsoleAppender" > <la Yout class= "Org.apache.log4j.PatternLayout" > <param name= "Conversionpattern" value= "%d{absolute}%5p%c{1}:%l- %m%n "/> </layout> </appender> <!--The following output log information to different files according to the level--> <!--set level to debug configuration information--> &L T;appender name= "DEBUG" class= "Org.apache.log4j.RollingFileAppender" > <param name= "File" value= "d:\\logs\\ App-debug.log "/> <param name=" Append "value=" true "/> <param name=" maxfilesize "value=" 500MB "/> ;p Aram Name= "Maxbackupindex" value= "2"/> <layout class= "org.apache.log4j.PatternLayout" > <param name= "Co Nversionpattern "value="%d{absolute}%5p%c{1}:%l-%m%n "/> </layout> <filter class=" Org.apache. log4j.varia.LevelRangeFilter "> <param name=" levelmin "value=" DEBUG "/> <param" name= "Levelmax" value= "DE BUG "/> </filter> </appender> <!--set Level info configuration information--> <appender name=" info class= "Org.apach E.log4j.rollingfileappender "> <param name=" File "value=" D:\\logs\\app-info.log "/>" <param name= "Append" V Alue= "true"/> <param name= "maxfilesize" value= "500KB"/> <param "name=" Maxbackupindex "2" value= & Lt;layout class= "Org.apache.log4j.PatternLayout" > <param name= "Conversionpattern" value= "%d{absolute}%5p%c{1 }:%l-%m%n "/> </layout> <filter class=" Org.apache.log4j.varia.LevelRangeFilter "> <param name=" L Evelmin "value=" info "/> <param name=" Levelmax "value=" INFO "/> </filter> </appender> <!-- Set level to WARN configuration information--> <appender name= "WARN" class= "Org.apache.log4j.RollingFileAppender" > <param name= "File "Value=" D:\\logs\\app-warn.loG "/> <param name=" Append "value=" true "/>" <param name= "MaxFileSize" value= "500KB"/> <param name= "Maxbackupindex" value= "2"/> <layout class= "org.apache.log4j.PatternLayout" > <param name= "Conversionpat" Tern "value="%d{absolute}%5p%c{1}:%l-%m%n "/> </layout> <filter class=" Org.apache.log4j.varia.LevelRan Gefilter "> <param name=" levelmin "value=" WARN "/>" <param name= "Levelmax" value= "WARN"/> </filte R> </appender> <!--set level for Deb configuration information--> <appender name= "ERROR" class= "org.apache.log4j.RollingFileApp" Ender "> <param name=" "File" value= "D:\\logs\\error.log"/> "<param" name= "Append" value= "true"/> <la Yout class= "Org.apache.log4j.PatternLayout" > <param name= "Conversionpattern" value= "%d{absolute}%5p%c{1}:%l- %m%n "/> </layout> <filter class=" Org.apache.log4j.varia.LevelRangeFilter "> <param name=" levelmin "Value=" ERROR "/> &LT;param name= "Levelmax" value= "ERROR"/> </filter> </appender> <!--configuration specifically to implement the way, this side only set the Stdout,error this 2
		Situation, no use of the situation, do not configure above, otherwise there will be error--> <root> <priority value= "info"/> <appender-ref ref= "STDOUT"/>  <appender-ref ref= "ERROR"/> </root> </log4j:configuration>


You can refer to the following 2 articles:

1 articles as the basis, 1 for internal excavation.

One: http://www.blogjava.net/zJun/archive/2006/06/28/55511.html

The log4j configuration file (Configuration file) is used to set the level, the repository, and the layout of the logger, and it can be set in key=value format or in XML format information. By configuring, you can create a log4j running environment.

1. configuration file
The basic format of the log4j configuration file is as follows: #配置根Logger
Log4j.rootlogger = [level], appenderName1, appenderName2, ...

#配置日志信息输出目的地Appender
Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Log4j.appender.appenderName.option1 = value1
...
Log4j.appender.appenderName.optionN = Valuen

#配置日志信息的格式 (Layout)
Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Log4j.appender.appenderName.layout.option1 = value1
...
Log4j.appender.appenderName.layout.optionN = Valuen
which[level]is the log output level, a total of 5 levels:
FATAL 0
ERROR 3
WARN 4
INFO 6
DEBUG 7

Appender for the log output destinations, LOG4J provides the following appender:
Org.apache.log4j.ConsoleAppender (console),
Org.apache.log4j.FileAppender (file),
Org.apache.log4j.DailyRollingFileAppender (a log file is generated every day),
Org.apache.log4j.RollingFileAppender (a new file is generated when the file size reaches the specified size),
Org.apache.log4j.WriterAppender (send log information to any specified place in streaming format)
Layout: Log output format, LOG4J provides the following layout:
Org.apache.log4j.HTMLLayout (layout in HTML form),
Org.apache.log4j.PatternLayout (You can specify layout patterns flexibly),
Org.apache.log4j.SimpleLayout (The level and information string that contains the log information),
Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)
Print Parameters:LOG4J uses a print format similar to the printf function in C to format log information as follows:
   %mThe message specified in the output code
   %pOutput priority, i.e. Debug,info,warn,error,fatal
   %rThe number of milliseconds to output from the application boot to the output of this log information
   %cThe class to which the output belongs, usually the full name of the class in which it is located
   %tOutput the name of the thread that generated the log event
Class name of the class to which the%f output log information belongs
   %nOutput a carriage return line break, Windows platform is "\ r \ n", Unix platform is "\ n"
   %dThe date or time of the output log point of time, the default format is ISO8601, or the format can be specified thereafter, for example:%d{yyy MMM dd hh:mm:ss,sss}, Output is similar: October 18, 2002 22:10:28,921
   %lThe location where the output log event occurs, including the class name, the thread that occurred, and the number of lines in the code. Example: Testlog4.main (testlog4.java:10)
Detailed


A outputs the name of the AppDomain that created the log
c default output logger full name. Followed by "{number}", the output corresponds to the number of the logger name level (starting from the right). If the full name is "A.B.C", the "%c{2}" Output "B.C"
C outputs the class name of the call logging request. The following can be followed by "{number}", which indicates that the output corresponds to the number of the class name (including namespaces, starting from the right).
d output Log time, followed by "{Time format}". The default is the
full name of the file requested by the YYYY-MM-DD hh:mm:ss,fff F output Call log record. (affects speed)
l outputs some local information that calls log records requests. such as class and member names, call files, and call declaration lines of code. (Extremely affecting performance)
L output the number of declaration lines for the call log record request. (Extremely affecting performance)
m outputs the information that the application will output.
the name of the member of the call log record requested by M output. (Extremely affect performance)
N output newline symbol
p output log Request level value
r output from application startup to log record request (milliseconds)
t output the thread name that generated the log, and the number of the output thread if there is no name
u outputs the name of the currently active user. (Principal.Identity.Name)
W outputs the Windows identity of the currently active user.
% output One%



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.