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. package com.joyoungzhang.log4j;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    public class Log4jModel {
    
    	private static final Log LOG = LogFactory.getLog(Log4jModel.class);
    
    	public static void main(String[] args) {
    		if (LOG.isErrorEnabled()) {
    			LOG.error("error......");
    		}
    		if (LOG.isInfoEnabled()) {
    			LOG.info("info......");
    		}
    		if (LOG.isDebugEnabled()) {
    			LOG.debug("debug......");
    		}
    	}
    
    }
    
    通过http://zy19982004.iteye.com/blog/1991328可以了解到,采用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

七.附件内容:commons-logging和Log4j整合的demo

一.Apache Log4j 二.Apache commons-logging 三.commons-logging怎样适配到合适的日志系统 四.使用Log4j和commons-logging  五.单独使用Log4j或commons-logging 六.你也可以阅读以下文档 七.附件内容:commons-logging和Log4j整合的demo

猜你喜欢

转载自zy19982004.iteye.com/blog/1867448