In the previous article to introduce you to the Java log4j Detailed tutorial, this article to introduce the Java Web log4j configuration and the Web project configuration log4j techniques. Please see below for details.
First to provide you with Log4j.jar download: http://logging.apache.org/log4j/1.2/download.html
Java Web project use log4j
1. Add in Web.xml file
<!--configuration log4j-->
<context-param>
<param-name>webAppRootKey</param-name>
< param-value>com.hsinghsu.testssh.webapp.root</param-value>
</context-param>
< context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/ web-inf/classes/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>600000</param-value >
2. Add log4j.properties File
Log4j.rootcategory=info, stdout, R Log4j.appender.stdout=org.apache.log4j.consoleappender Log4j.appender.stdout.layout=org.apache.log4j.patternlayout LOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=[QC] %p [%t]%c.%m (%l) | %m%n Log4j.appender.r=org.apache.log4j.dailyrollingfileappender #log4j. Appender.r.file=e:\\test\\avatar.log # Linux logs file path #log4j. Appender.r.file=${com.hsinghsu.testssh.webapp.root}/log/testlog.log # # Windows logs file pa Th Log4j.appender.r.file=d:\\eclipsespace\\testssh\\webcontent\\web-inf\\testlog.log log4j.appender.R.layout= Org.apache.log4j.PatternLayout #log4j. appender.r.layout.conversionpattern=%d-[ts]%p%t%c-%m%n # Log4j.logger.com.neusoft=debug #log4j. Logger.com.opensymphony.oscache=error Log4j.logger.net.sf.navigator=info #
Log4j.logger.org.apache.commons=error #log4j. Logger.org.apache.struts=warn #log4j. Logger.org.displaytag=error Log4j.logger.org.springframework=info # #log4j. Logger.com.ibatis.db=warn #log4j. logger.org.aPache.velocity=fatal #log4j. Logger.com.canoo.webtest=warn #log4j. logger.org.hibernate.ps.preparedstatementcache= WARN #log4j. Logger.org.hibernate=debug log4j.logger.org.hibernate=info #log4j. Logger.org.logicalcobwebs=warn
3. Use of log4j
For example, use log4j in Userserviceimpl.java.
package Com.hsinghsu.testSSH.service.impl;
Import Org.apache.log4j.Logger;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
Import Com.hsinghsu.testSSH.dao.UserDao;
Import Com.hsinghsu.testSSH.model.User;
Import Com.hsinghsu.testSSH.service.UserService; @Service (value = "UserService") public class Userserviceimpl implements userservice{@Autowired private Userdao UserD
Ao
Private final static Logger Logger = Logger.getlogger (Userserviceimpl.class);
Private Logger Logger = Logger.getlogger (This.getclass (). GetName ()); public boolean login (string name, string password) {logger.info ("--userserviceimpl Login method Name: +name+" Passwo
RD: "+password);
User user = Userdao.getuserbyname (name);
if (user!=null) {if (Password.equals (User.getpwd ())) {return true;
return false; }
}
Second, log4j.properties parameter detailed
Log levels are divided into debug (debug information), info (general information), warn (warning message), error (Error message), Fatal (fatal error message).
LOG4J supports two configuration file formats, one in XML format and one for Java property file Log4j.properties, which is described in log4j.properties as an example.
1. Configure Root Logger
Logger is responsible for most of the operations of logging, with the following syntax:
Log4j.rootlogger = [level], appenderName1, appenderName2, ...
Level: Is the priority of logging, divided into off, FATAL, ERROR, WARN, INFO, DEBUG, all, or levels you define.
Appendername: Is the name of the destination that specifies the output of the log information.
such as: LOG4J.ROOTLOGGER=INFO,A1,B2,C3
In earlier log4j versions, Org.apache.Category implemented the logger's functionality and later extended the category class using logger, so log4j.rootcategory could also use it.
such as: LOG4J.ROOTCATEGORY=INFO,A1,A2
2, configuration log information output destination Appender
Appender is responsible for controlling the output of the logging operation, and its syntax is:
Log4j.appender.appenderName = Fully.qualified.name.of.appender.class
Among them "Fully.qualified.name.of.appender.class" has the following several:
I.org.apache.log4j.consoleappender (console)
This option is available in the following ways:
Threshold=warn: 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
Ii.org.apache.log4j.FileAppender (file)
This option is available in the following ways:
Threshold=warn: 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.
Iii.org.apache.log4j.DailyRollingFileAppender (Generate a log file every day)
This option is available in the following ways:
Threshold=warn: 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=a.log: Specifies that the message output to the A.log file, by default, starts at the root path of the Web server.
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.
Datepattern= '. ' YYYY-WW: Scrolls the file once a week, that is, a new file is generated each week. Of course, you can specify the month, week, day, time, and minutes. The corresponding format is as follows:
'.' YYYY-MM: Monthly
'.' YYYY-WW: Weekly
'.' YYYY-MM-DD: Every day
'.' Yyyy-mm-dd-a: two times a day
'.' YYYY-MM-DD-HH: Per hour
'.' YYYY-MM-DD-HH-MM: Per minute
Iv.org.apache.log4j.RollingFileAppender (when the file size reaches a specified size, a new file is generated and can be passed through the log4j.appender.appendername.maxfilesize= 100KB Set File size)
This option is available in the following ways:
Threshold=warn: 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=a.log: Specifies that the message output to the A.log file, by default, starts at the root path of the Web server.
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.
V.org.apache.log4j.writerappender (send log information to any specified place in streaming format)
For example:
Log4j.appender.r=org.apache.log4j.dailyrollingfileappender
Log4j.appender.r.file=d:\\eclipsespace\\testssh\\webcontent\\web-inf\\testlog.log
3, configuration log Information Format (layout) Layout
Layout is responsible for formatting the output of Appender, whose syntax is:
Log4j.appender.appenderName.layout = Fully.qualified.name.of.layout.class
Among them "Fully.qualified.name.of.layout.class" has the following several:
I.org.apache.log4j.htmllayout (layout in HTML tabular format)
This option is available in the following ways:
Locationinfo=true: Default value is false, output Java file name and line number
Title=my app File: The default value is log4j Log Messages.
Ii.org.apache.log4j.PatternLayout (flexibility to specify layout patterns)
This option is available in the following ways:
conversionpattern=%m%n: Specifies how to format the specified message
The meanings of%m%n and other symbols are as follows:
-X: Left-aligned when x information is output;
%p: Output log information priority, i.e. 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, for example:%d{yyy MMM dd hh:mm:ss,sss}, Output is similar: October 18, 2002 22:10:28,921
%r: The number of milliseconds to output from the application boot to the output of this log information
%c: The class that the output log information belongs to, usually the full name of the class in which it is located
%t: Output The name of the thread that generated the log event
%l: The location 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 lines in the code. 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 was generated
%l: line number in output code
%M: The message specified in the output code, the resulting log specific information
%n: Output a carriage return line break, Windows platform for "\ r \ n", Unix platform for "\ n" Output log message Wrapping
You can control the minimum width, the maximum width, and the alignment of text by adding modifiers between% and pattern characters. Such as:
%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.
%-20C: Specifies the name of the output category, the minimum width is 20, and if category's name is less than 20, the "-" number specifies left-aligned.
%.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.
%20.30C: If the name of the category is less than 20 to fill the space, and the right alignment, if its name is longer than 30 characters, from the left side of the exported characters are cut off.
such as:%-4r%-5p%d{yyyy-mm-dd HH:mm:ssS}%c%m%n
[TEST]%p [%t]%c.%m (%l) | %m%n
Iii.org.apache.log4j.SimpleLayout (level and information string that contains log information)
Iv.org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log was generated)
4. Other
log4j.logger.com. Neusoft =debug
Specifies that all classes under the Com.neusoft package have a level of debug.
Log4j.logger.com.opensymphony.oscache=error
Log4j.logger.net.sf.navigator=error
These two sentences are to set the error level of the two packages to be errors, if there is no configuration Ehcache in the project, you do not need these two sentences.
Log4j.logger.org.apache.commons=error
Log4j.logger.org.apache.struts=warn
These two sentences are struts ' packages.
Log4j.logger.org.displaytag=error
This is Displaytag's bag. (For the QC Issues List page)
Log4j.logger.org.springframework=debug
This sentence is a spring package.
Log4j.logger.org.hibernate.ps.preparedstatementcache=warn
Log4j.logger.org.hibernate=debug
These two sentences are Hibernate's bag.
Third, write log to multiple files.
LOG4J configuration:
Log4j.rootcategory=info,stdout
Log4j.appender.stdout=org.apache.log4j.consoleappender
Log4j.appender.stdout.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.STDOUT.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD Hh\:mm\:ss,sss}[colorclouds]%p [%t]%C.%M (%L) | %m%n
Log4j.logger.net.sf.navigator=info
Log4j.logger.org.springframework=info
Log4j.logger.runlogger= Info,r
Log4j.appender.r=org.apache.log4j.rollingfileappender
Log4j.appender.r.file=g:\\log\\runlog.log
log4j.appender.r.maxfilesize=51200kb
#log4j. Appender.r.file=${com.huawei.icity.webapp.root}/log/icity.log
Log4j.appender.r.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.R.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD Hh\:mm\:ss,sss}[colorclouds Run]%p [%t]%C.%M (%L) | %m%n
#log4j. logger.businesslogger= info,b
#log4j. Appender.b=org.apache.log4j.rollingfileappender
#log4j. Appender.b.file=g:\\log\\businesslog.log
#log4j. appender.b.maxfilesize=51200kb
#log4j. appender.b.layout=org.apache.log4j.patternlayout
#log4j. Appender.b.layout.conversionpattern=%d{yyyy-mm-dd hh\:mm\:ss,sss}[colorclouds Business]%p [%t]%C.%M (%L) | %m%n
Log4j.logger.interfacelogger= Info,i
Log4j.appender.i=org.apache.log4j.rollingfileappender
Log4j.appender.i.file=g:\\log\\interfacelog.log
log4j.appender.i.maxfilesize=51200kb
Log4j.appender.i.layout=org.apache.log4j.patternlayout
LOG4J.APPENDER.I.LAYOUT.CONVERSIONPATTERN=%D{YYYY-MM-DD Hh\:mm\:ss,sss}[colorclouds Interface]%p [%t]%C.%M (%L) | %m%n
Java Call:
Import Org.apache.commons.logging.Log;
Import org.apache.commons.logging.LogFactory;
public class Querymymeetingaction extends Baseflowaction
{
/**
* UID
/
private static final long Serialversionuid = 7612831197603586815L;
private static Log Runlog = Logfactory.getlog ("Runlogger");//run log
private static log Interfacelog = Logfactory.getlog ("Interfacelogger");/interface Log public
String execute () throws Exception
{
Interfacelog.info ("====>> request");
Runlog.info ("request");
return Super.execute ();
}
Here are some ways to configure log4j in a Web project
1. Dynamic changes to record levels and policies do not require the restart of Web applications, as described in "effective Enterprise Java."
2. Set the log file in/web-inf/logs/without the need to write an absolute path.
3. Log4j.properties can be put together with other properties in/web-inf/, not class-path.
Add in Web.xml
<!--if webapprootkey parameters are not defined, then Webapprootkey is the default "Webapp.root"-->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>xxx.root </param-value>
</context-param>
<context-param>
<param-name> Log4jconfiglocation</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jrefreshinterval</ param-name>
<param-value>60000</param-value>
</context-param>
<listener >
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
In the above configuration, Log4jconfiglistener will go to web-inf/log4j.propeties read the configuration file;
Open a watchdog thread every 60 seconds to scan the configuration file changes;
and push the path of the Web directory into a system variable called Webapp.root.
Then, you can define the logfile position in the log4j.properties.
Log4j.appender.logfile.file=${webapp.root}/web-inf/logs/myfuse.log
If you have multiple Web applications that are afraid of webapp.root variable repetition, you can define Webapprootkey in Context-param.
The above is the article on the in-depth analysis of Java Web log4j configuration and in the Web project configuration log4j skills, I hope to learn about the Java Web log4j related knowledge to help.