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可以自动使用其他日志模块
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小夏天禧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值