commons-logging

commons-logging是Apache commons类库中的一员。Apache commons类库是一个通用的类库,提供了基础的功能,比如说commons-fileupload,commons-httpclient,commons-io,commons-codes等。

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

commons-logging的使用类似于Log4j,他们的级别以及使用规则是完全一样的。下面来一个demo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package org.linkinpark.commons.commonslogging;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
/**
* @创建作者: LinkinPark
* @创建时间: 2016年2月26日
* @功能描述: commons-logging的测试类
*/
public class CommonsLoggingTest
{
public static Log LOG = LogFactory.getLog(CommonsLoggingTest.class);

@Test
public void test()
{
LOG.debug("debug()...");
LOG.info("info()...");
LOG.error("error()...");
}
}

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

现在我们在项目中不要添加log4j的依赖,看下效果。

1
2
3
4
二月 26, 2016 10:34:23 上午 org.linkinpark.commons.commonslogging.CommonsLoggingTest test
信息: info()...
二月 26, 2016 10:34:23 上午 org.linkinpark.commons.commonslogging.CommonsLoggingTest test
严重: error()...

在添加 log4j.properties 配置文件后:

1
2
3
[2016-02-26 10:47:13]-[main-DEBUG]-[org.linkinpark.commons.commonslogging.CommonsLoggingTest-test(19)]: debug()...
[2016-02-26 10:47:13]-[main- INFO]-[org.linkinpark.commons.commonslogging.CommonsLoggingTest-test(20)]: info()...
[2016-02-26 10:47:13]-[main-ERROR]-[org.linkinpark.commons.commonslogging.CommonsLoggingTest-test(21)]: error()...

总结
严格的说,commons-logging不是一个日志控件,没有日志功能,它只是统一了JDK Logging与Log4j的API,并把日志功能交给JDK Loggings或者是log4j。对于不能确定日志方式的系统,commons-logging是一个不错的选择,Spring,Hibernate,Struts等使用的都是commons-logging。下一篇我们会研究下Commons-logging的源码,来深入的整理下Commons-logging。

文章作者: Ammar
文章链接: http://lizhaoloveit.cn/2019/08/05/commons-logging/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Ammar's Blog
打赏
  • 微信
  • 支付宝

评论