Log4j 配置文件放置位置说明

一般我们直接将log4j.properties放置在src目录下,这样系统自动会找到的,其实就是放在WEB-INF/classes文件下。这个路径在classpath下,所以直接就能找到。我们写Logger的时候如下
public class HelloLog4j {
  
    public static Logger logger = Logger.getLogger(HelloLog4j.class);

    public static void main(String[] args) {       
        logger.debug("This is debug message.");
        logger.info("This is info message.");
        logger.error("This is error message.");
        xxx();
    }
    
    public static void xxx(){
        logger.debug("main method has invoked xxx method.");
    }
}

如果现在我们想把log4j.properties文件放置在其它目录下,例如:WEB-INF下和web.xml放在一起。这时候就需要我们手动指定log4j配置文件的路径,否则系统是找不到的。

一、首先我们在web.xml中配置好log4j.properties路径:

      <context-param>

            <param-name>log4jConfigLocation</param-name>
            <param-value>/WEB-INF/log4j.properties</param-value>
        </context-param>

二、然后写个servlet,部分代码如下:

public void init() {
    String prefix = getServletContext().getRealPath("/");
    String file = getInitParameter("log4jConfigLocation");
    if (file != null) {
      PropertyConfigurator.configure(prefix + file);     
    }
}

三、在web.xml中配置servlet,并将log4jConfigLocation加入到Servlet中,让其Server启动即运行:

<servlet>

   <servlet-name>your servlet</servlet-name>

   <servlet-class>your servelt class</servlet-class>

   <init-param>

      <param-name>log4jConfigLocation</param-name>

      <param-value>/WEB-INF/log4j.properties</param-value>

    </init-param>

   <load-on-startup>1</load-on-startup>

</servlet>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值