日志API改进:用commons-log还是slf4j?这是一个问题!
用commons-log还是slf4j?这是一个问题!
看jdk中的logger不爽,最早直接用Log4j,后来参考Spring主要用commons-log,再后来看见很多新的开源项目如mina2等都采用了slf4j日志系统。我个人还是比较喜欢格式化的输出的方式,避免Spring中大量出现的 if (_log.isDebugEnabled())条件判断语句。对slf4j还有点不爽的,就是后面的参数最多只能定义2个。在jdk1.5中,允许定义可变数目的参数,因而可以有更好的封装方式。可以定义如下,那么以后封装的系统,只有MyLog与日志API直接依赖(commons-log、slf4j),所以很容易在不同的日志系统间切换。
public interface MyLogInf { public void debug(String message, Object... args); public void info(String message, Object... args); public void warn(String message, Object... args); public void error(Throwable e, String message, Object... args); public boolean isDebugEnabled();//仅仅用于打印辅助调试信息(而在debug()中已经,无需单独代码调用)}public class MyLog implements MyLogInf{ public static MyLog getLog(Class clz){ return new MyLog(clz.getName()); } public static MyLog getLog(String clz) { return new MyLog(clz); } static MyLogInf getLogger(){ return getLog(MyLog.class);}//------------------ 方案1//private org.apache.commons.logging.Log _log = null;//public MyLog(String clz) { _log = org.apache.commons.logging.LogFactory.getLog(clz);}//------------------ 方案2private org.slf4j.Logger _log = null; public MyLog(String clz) { _log = org.slf4j.LoggerFactory.getLogger(clz);}//------------------ public void debug(String message, Object... args){ if (_log.isDebugEnabled())_log.debug(String.format(message, args)); } public void info(String message, Object... args) { if (_log.isInfoEnabled())_log.info(String.format(message, args)); } public void warn(String message, Object... args){ if (_log.isWarnEnabled())_log.warn(String.format(message, args)); } public void error(Throwable e, String message, Object... args){ if (_log.isErrorEnabled())_log.error(String.format(message, args), e); }//------------------ public boolean isDebugEnabled() { return _log.isDebugEnabled(); }}