log4j按级别分类输出日志到相对路径日志文件

按级别分类输出日志 log4j.xml配置示例






 
 
  	
    
      
    
  

  
    
    
    
    
    
      
    
  

  

    
    
    
    
      
    
    
    	
	
	
    
  
  
	
  		
 	
 	
  	
		
		
		
		
	
	

 

节点的顺序不能乱,不然会报错的

写个servlet(是这么拼写吧)自己指定log4j.xml的位置顺便解决一哈日志文件相对路径的问题

package util;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

public class Log4jInit extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(Log4jInit.class);

	public void init() {
		String path = this.getServletContext().getRealPath("/");
		String file = this.getInitParameter("log4j_init_path");
		String logFile = this.getInitParameter("log4j_logfile_path");
		System.setProperty("logfilepath", path+logFile);
		if (file != null) {
//			Properties prop = new Properties();
			try {
//				prop.load(new FileInputStream(path + file)); // 加载log4j.properties
				// 设置日志文件的输出路径
//				prop.setProperty("log4j.appender.file.File", path + logFile + prop.getProperty("log4j.appender.file.File"));
//				prop.setProperty("log4j.appender.file_sql.File", path + logFile + prop.getProperty("log4j.appender.file_sql.File"));
				// 加载配置项
//				PropertyConfigurator.configure(prop);
				DOMConfigurator.configure(path + file);
				super.init();
			} catch (Exception e) {
				logger.info("初始化log4j日志输入路径异常,请检查web.xml参数配置是否正常,异常发生在" + this.getClass().getName() + "类的public void init()方法,异常的原意是:"
						+ e.getMessage(), e.fillInStackTrace());
			}
		}
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}
}

注释部分是配置log4j.properties的,不过log4j.properties貌似不能按级别分类输出日志(就是把不同级别的信息输出到不同的文件里)

另附web.xml的相关配置

 

。。。。。。。。。

	lo4jInit
	util.Log4jInit
	
		log4j_init_path
		WEB-INF\log4j.xml
	
	
		log4j_logfile_path
		WEB-INF\
	
	0

。。。。。。。。。



 

你可能感兴趣的:(java,web)