Java日志学习一:Log4j和commons-logging的关系

一.Apache Log4j

  1.  http://logging.apache.org/log4j/2.x/
  2. 提供了全面的日志管理。

二.Apache commons-logging

  1. http://commons.apache.org/proper/commons-logging/ 
  2. there are many logging implementations out there,The Logging package is an ultra-thin bridge between different logging implementations...
  3. 翻译过来:
  • commons-logging是一个简单的适配器,为各种各样的日志实现提供了统一的接口。
  • 当变化日志实现时,application不需要做任何改变。
  • commons-logging也提供了简单的日志实现,但不推荐使用。

三.commons-logging怎样适配到合适的日志系统

1) 首先在classpath下寻找自己的配置文件commons-logging.properties,如果找到,则使用其中定义的Log实现类;

2) 如果找不到commons-logging.properties文件,则在查找是否已定义系统环境变量org.apache.commons.logging.Log,找到则使用其定义的Log实现类;

3) 否则,查看classpath中是否有Log4j的包,如果发现,则自动使用Log4j作为日志实现类;

4) 否则,使用JDK自身的日志实现类(JDK1.4以后才有日志实现类);

5) 否则,使用commons-logging自己提供的一个简单的日志实现类SimpleLog;

四.使用Log4j和commons-logging 

  1. 项目里加入log4j.jar和commons-logging.jar,加入classpath下。
  2. 新建log4j.properties,加入classpath下。
  3. Java代码   收藏代码
    1. package com.joyoungzhang.log4j;  
    2.   
    3. import org.apache.commons.logging.Log;  
    4. import org.apache.commons.logging.LogFactory;  
    5.   
    6. public class Log4jModel {  
    7.   
    8.     private static final Log LOG = LogFactory.getLog(Log4jModel.class);  
    9.   
    10.     public static void main(String[] args) {  
    11.         if (LOG.isErrorEnabled()) {  
    12.             LOG.error("error......");  
    13.         }  
    14.         if (LOG.isInfoEnabled()) {  
    15.             LOG.info("info......");  
    16.         }  
    17.         if (LOG.isDebugEnabled()) {  
    18.             LOG.debug("debug......");  
    19.         }  
    20.     }  
    21.   
    22. }  
    通过采用org.apache.commons.logging.impl.LogFactoryImpl作为LogFactory,去实例化一个Log4JLogger对象。

 

五.单独使用Log4j或commons-logging

  1.  单独使用Log4j,在编程复杂度上比一起使用Log4j和commons-logging更低,但整个系统与Log4j是耦合的,有一天我不想使用Log4j了,整个系统都得改。
  2. 单独使用commons-logging当然也可以,但commons-logging的作用体现在“为所有的日志实现提供统一的接口”,本身并没有强大的日志实现系统,所以也不推荐。

六.你也可以阅读以下文档

  1. http://commons.apache.org/proper/commons-logging/
  2. http://logging.apache.org/log4j/2.x/
  3. http://www.cnblogs.com/80houboy/archive/2012/01/02/commons-logging_commons-log4j.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值