log4j区分日志和debug信息输出到指定目录文件
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.logger.Audit= DEBUG,R
log4j.logger.debug= DEBUG, stdout
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=log4jDemo.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c %C %M - %m%n
添加审计类audit.java
package com.common.logging;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
public class AuditLogger {
static Log log = LogFactory.getLog("Audit");
static Logger loger = Logger.getLogger("Audit"); //两种方式都可以
public static void trace(Object message){
log.trace(message);
}
public static void debug(Object message){
log.debug(message);
}
public static
void error(Object message){
log.error(message);
}
public static
void fatal(Object message){
log.fatal(message);
}
public static
void info(Object message){
log.info(message);
}
}
其他日志也可以类似使用
static Logger loger = Logger.getLogger("debug");
同时为了使日志文件能够初始化到目标目录需要添加Log4jInit.java
package com.common.logging;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Log4jInit extends HttpServlet {
public Log4jInit(){
}
public void init(ServletConfig config) throws ServletException{
String prefix = config.getServletContext().getRealPath("\");
String destprefix = prefix+"logs\";
String file = config.getInitParameter("log4j");
String filePath = prefix+file;
Properties props = new Properties();
try{
String strProp = "log4j.appender.R.File";
FileInputStream istream = new FileInputStream(filePath);
props.load(istream);
istream.close();
String logFile = destprefix+props.getProperty(strProp);
props.setProperty(strProp, logFile);
PropertyConfigurator.configure(props);
}
catch(IOException ex){
System.out.println("Read configuration file ["+filePath+"] failed");
return;
}
}
}
然后再web.xml中配置如下
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>com.common.logging.Log4jInit</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF\log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>