Log4j详细介绍(二)Commonslogging控件

  除了Log4j还有一种选择是使用commons-logging。commons-logging是Apache commons类库中的一员。Apache commons类库是一个通用的类库,提供了基础的功能,例如commons-fileupload,commons-httpclient,commons-io,commons-codec等

  commons-logging能够选择使用Log4j还是JDK Logging,但不依赖与Log4j,JDK logging的API。如果项目的classpath中包含log4j的类库,则使用Log4j,否则使用JDK Logging,使用commons-logging能够灵活地选择使用哪种日志方式,而不需要修改源代码。

  commons-logging的使用类似于Log4j,它们的级别以及使用规则完全一样的,例如:

 1 import org.apache.commons.logging.Log;
 2 import org.apache.commons.logging.LogFactory;
 3 
 4 public class CommonsLoggingTest {
 5 
 6     public static Log log = LogFactory.getLog(CommonsLoggingTest.class);
 7 
 8     public static void main(String[] args) {
 9         log.trace("trace信息");
10         log.debug("debug信息");
11         log.info("info信息");
12         log.warn("warn信息");
13         log.error("errof信息");
14         log.fatal("fatal信息");
15         try {
16             String s = null;
17             s.length();
18         } catch (Exception e) {
19             log.trace("trace一个异常", e);
20             log.debug("debug一个异常", e);
21             log.info("info一个异常", e);
22             log.warn("warn一个异常", e);
23             log.error("error一个异常", e);
24             log.fatal("fatal一个异常", e);
25         }
26     }
27 
28 }

如果有log4j,commons-logging会把输出原封不动交给log4j。如果没有log4j ,commons-logging会将相应的输出转换为JDK Logging的输出。

  默认地,commons-logging会自动检查是否使用log4j。也可以使用配置文件显示的启动log4j.配置文件为commons-logging.properties,放到程序的classpath下即可,例如:

1 org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
2 org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.LogFactoryImpl

   严格来说,commons-logging不是弱智控件,没有日志功能。它只是统一了JDK Logging和Log4j的API,并把日志功能JDK Logging或者Log4j。对于不能确定的日志系统commons-logging是个不错的选择,Spring,Hibernate,Struts等都使用的是commons-logging

原文地址:https://www.cnblogs.com/ArtsCrafts/p/Log4j2.html