您好,登录后才能下订单哦!
本篇内容介绍了“Log4j中相对路径的问题怎么解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
一、properties文件中:
log4j.appender.logfile.File=${WORKDIR}/logs/app.log
其中“${WORKDIR}/”是个变量,会被System Property中的“WORKDIR”的值代替。这样,我们就可以在log4j加载配置文件之前,先用System.setProperty设置好根路径。
jsp中可以这样:
String path = pageContext.getServletContext().getRealPath("/");
 String realPath = path+"WEB-INFclasseslog4j.properties";
 System.setProperty("WORKDIR",path.replace("","/"));
 PropertyConfigurator.configure(realPath.replace("","//"));//加载.properties文件
[@more@]
二、可以使用环境变量(没试过网上看的)
log4j.appender.R=org.apache.log4j.RollingFileAppender 
log4j.appender.R.File=${catalina.base}/logs/logs_tomcat.log 
log4j.appender.R.MaxFileSize=10KB
三、具体实现:(没试过网上看的)
一般在我们开发项目过程中,log4j日志输出路径固定到某个文件夹,这样如果我换一个环境,日志路径又需要重新修改,比较不方便,目前我采用了动态改变日志路径方法来实现相对路径保存日志文件
 (1).在项目启动时,装入初始化类: 
 public class Log4jInit extends HttpServlet {    
  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();            
    //toPrint(props.getProperty("log4j.appender.file.File"));            
    String logFile = prefix + props.getProperty("log4j.appender.file.File");//设置路径            
    props.setProperty("log4j.appender.file.File",logFile);            PropertyConfigurator.configure(props);
    //装入log4j配置信息        
   } catch (IOException e) {
    toPrint("Could not read configuration file [" + filePath + "].");            
    toPrint("Ignoring configuration file [" + filePath + "].");            
    return;
   }    
  }    
  public static void toPrint(String content) {        
   System.out.println(content);    
  }
 }
 
 (2).Web.xml中的配置
  
  
  
  
  
  
“Log4j中相对路径的问题怎么解决”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。