log4j将日志输出到相对目录

很简单,我喜欢将Log跟着webRoot走,这样随便你项目移到哪,都可以直接运行,不要再运行这运行那。

 

思路是写一个初始化log4j的servlet。

 

 

 

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); 
         } 
} 

 

 

 

 

 

refurl:http://sharep.blog.51cto.com/539048/143734

 

http://ziqiang0501.iteye.com/blog/280755 ,有spring的配置,具体如下:

 

由于spring也会加载log4j.properties,如果加载不到就往控制台打log信息,总觉得有些碍眼,于是想办法去掉。Spring提供了一个Log4jConfigListener,本身就能通过web.xml中配置来指定位置加载log4j配置文件和log输出路径,注意该listener需要放在spring的Listener之前。 
事实上,Log4jConfigListener更适合log4j在web工程中使用,原因如下: 
  1. 动态的改变记录级别和策略,不需要重启Web应用,如《Effective Enterprise Java》所说。 
   2. 把log文件定在 /WEB-INF/logs/ 而不需要写绝对路径。 
因为 系统把web目录的路径压入一个叫webapp.root的系统变量。这样写log文件路径时不用写绝对路径了. 
log4j.appender.logfile.File=${webapp.root}/WEB-INF/logs/myfuse.log 
   3. 可以把log4j.properties和其他properties一起放在/WEB-INF/ ,而不是Class-Path。 
   4.log4jRefreshInterval为60000表示 开一条watchdog线程每60秒扫描一下配置文件的变化; 

 

在web.xml 添加 

<context-param>    
    <param-name>log4jConfigLocation</param-name>    
    <param-value>WEB-INF/log4j.properties</param-value>    
</context-param>    
    
<context-param>    
    <param-name>log4jRefreshInterval</param-name>    
    <param-value>60000</param-value>    
</context-param>    
    
<listener>    
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>    
</listener>    

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值