利用servlet初始化时配置log的存放位置
相关配置
log4j文件
java 代码
- package cn.feigme.util;
- 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;
- /**
- * Feigme H.Guo
- */
- public class Log4jInit extends HttpServlet {
- private static final long serialVersionUID = 1L;
- private static Logger logger = Logger.getLogger(Log4jInit.class);
- public Log4jInit() {
- }
- public void init(ServletConfig config) throws ServletException {
- String prefix = config.getServletContext().getRealPath("/");
- String file = config.getInitParameter("log4j");
- String filePath = prefix + file;
- Properties props = new Properties();
- try {
- FileInputStream istream = new FileInputStream(filePath);
- props.load(istream);
- istream.close();
- String logFile = prefix + props.getProperty("log4j.appender.logfile.File");//设置路径
- props.setProperty("log4j.appender.logfile.File",logFile);
- PropertyConfigurator.configure(props);//装入log4j配置信息
- logger.info(logFile);
- } catch (IOException e) {
- logger.debug("Could not read configuration file [" + filePath + "].");
- logger.debug("Ignoring configuration file [" + filePath + "].");
- return;
- }
- }
- }
相关配置
xml 代码
- <!-- log4j config -->
- <servlet>
- <servlet-name>log4j-init</servlet-name>
- <servlet-class>cn.feigme.util.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>
- <!-- log4j config -->
log4j文件
java 代码
- # For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
- # For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
- log4j.rootLogger=INFO, stdout, logfile
- log4j.appender.stdout=org.apache.log4j.ConsoleAppender
- log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
- log4j.appender.logfile=org.apache.log4j.RollingFileAppender
- log4j.appender.logfile.File=cis.log
- log4j.appender.logfile.MaxFileSize=1024KB
- # Keep three backup files.
- log4j.appender.logfile.MaxBackupIndex=3
- # Pattern to output: date priority [category] - message
- log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
- log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n