3Java异常处理——2断言和日志——3使用Commons Logging(廖雪峰)

1.Commons Logging

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

  • 可以挂接不同的日志系统
  • 可以通过配置文件指定挂接的日志系统
  • 自动搜索并使用Log4j
  • 使用JDK Logging(JDK >= 1.4)
public class Main{
    public static void main(String[] args){
        Log log = LogFactory.getLog(Main.class);
        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());
}

//在父类中实例化Log:
public abstract class Base{
    protected final Log log = LogFactory.getLog(getClass());
}

如何导入Commons Logging的jar包:

1.下载Commons Logging的jar包。导入jar包
http://commons.apache.org/proper/commons-logging/download_logging.cgi
选择binary的tar包或zip,解压即可。

2.将第一步中所下载的压缩包解压,找到名为commons-logging-1.2.jar的文件

3.打开Eclipse,选中项目单击右键,选中Properties,Java Build Path-Libraries-Add JARs

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;
    }	
}
public class Main {
    static final Log log = LogFactory.getLog(Main.class);
    public static void main(String[] args) {
        Person p = new Person("xiao ming");
	log.info(p.hello());
	try{
            new Person(null);
	}catch (Exception e) {
	    log.error("Exception",e);
	}	
    }
}

2.总结

  • Commons Logging是使用最广泛的日志模块
  • Commons Logging的API非常简单
  • Commons Logging可以自动使用其他日志模块

猜你喜欢

转载自blog.csdn.net/qq_24573381/article/details/107740015