廖雪峰Java3异常处理-2断言和日志-3使用Commons Logging
Commons Logging是Apache创建的日志模块:
- 可以挂接不同的日志系统
- 可以通过配置文件指定挂接的日志系统
- 自动搜索并使用Log4j
- 如果Log4j不存在,使用JDK Logging(JDK >= 1.4)
下载Commons Logging的jar包。导入jar包
http://commons.apache.org/proper/commons-logging/download_logging.cgi
选择binary的tar包或zip,解压即可。
IDEA:file-project structure-Modules-Dependencies, + -> 1 Jars or Directories-选择相应的jar包
eclipse:选择项目-properties-Java Build Path-Libraries-Add JARs
注意:jar包统一存在lib目录下,便于管理。
测试一下,导入成功
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Main {
public static void main(String[] args){
Log log = LogFactory.getLog(Main.class);//Main.class获得了log实例
log.info("start...");
log.warn("end...");
}
}
![](https://img2018.cnblogs.com/blog/1418970/201901/1418970-20190130171455993-1659020448.png)
Commons Logging定义了6个日志级别:
- FATAL 非常严重的错误
- ERROR
- WARNING
- INFO 默认
- DEBUG
- TRACE
//在静态方法中引用Log
public class Main {
static final Log log = LogFactory.getLog(Main.class);
}
//在实例方法中引用Log
public class Person{
final Log log = LogFactory.getLog(getClass());//getClass()传入当前类的对象
}
//在父类中实例化Log
public abstract class Base{
protected final Log log = LogFactory.getLog(getClass());
}
实例1
person.java
public class Person {
String name;
public Person(String name){
if (name == null){
throw new IllegalArgumentException("name is null");
}
this.name = name;
}
public String hello(){
return "Hello, "+this.name;
}
}
Main.java
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Main {
static final Log log = LogFactory.getLog(Main.class);
public static void main(String[] args){
Person p = new Person("小明");
log.info(p.hello());
try{
new Person(null);
}catch (Exception e){
log.error("Exception ",e);
}
}
}
![](https://img2018.cnblogs.com/blog/1418970/201901/1418970-20190131093901167-1543510003.png)
总结
- Commons Logging是使用最广泛的日志模块
- Commons Logging的API非常简单
- Commons Logging可以自动使用其他日志模块