廖雪峰Java3异常处理-2断言和日志-3使用Commons Logging

Commons Logging是Apache创建的日志模块:

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...");
    }
}

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);
        }
    }
}

总结

  • Commons Logging是使用最广泛的日志模块
  • Commons Logging的API非常简单
  • Commons Logging可以自动使用其他日志模块
posted on 2019-01-29 19:59  singleSpace  阅读(302)  评论(0编辑  收藏  举报