今天没事儿,研究了一下log4j,发现通过以下方法可以配置log4j相对于项目的路径,而不用写绝对路径.这样对于项目的部署来说实在是再方便不过了.如果有什么地方说的不对的,欢迎发表评论哦!
绝对路径的方法这里就不介绍了,网上很多.不会log4j的朋友可以随便找找例子,很快就入手了.
对于项目,首先把log4j的配置文件log4j.properties放在WEB-INF下,一般配置文件最好不要放在src下,不是很安全
对于jsp页面要用到log4j时可以写如下代码
String prefix = getServletContext().getRealPath("/");
PropertyConfigurator.configure(prefix+"\\WEB-INF\\log4j.properties") ;
Logger logger = Logger.getLogger(this.getClass().getName()) ;
对于java类中可以写如下代码
String s = JudgeUpLoad.class.getClassLoader().getResource("").toString() ;
int l = s.lastIndexOf("classes/") ;
int b = s.indexOf("/")+1 ;
String ne = s.substring(b, l).replace('/', '\\')+"\\log4j.properties" ;
PropertyConfigurator.configure(ne) ;
Logger logger = Logger.getLogger(this.getClass().getName()) ;
对于J2EE来说,不管是jsp,还是java类,java都有找到其自身文件路径的方法.除了上边列出的,还有如下方法
Thread.currentThread().getContextClassLoader().getResource("")
JudgeUpLoad.class.getClassLoader().getResource("")
JudgeUpLoad.class.getResource("/")
JudgeUpLoad是类名,以上语句打印出的结果都是file:/D:/tomcat-6.0.14/webapps/Log4j/WEB-INF/classes/ 然后经过字符串的拆分,组合就可以得到
配置文件的绝对路径了。只是目前这种方法还没有在linux环境下测试过,不知道linux下是否可以。