发布于 2016-10-30 09:36:16 | 326 次阅读 | 评论: 0 | 来源: PHPERZ
很多时候我们为了在类中加日志不得不写一行,而且还要去手动改XXX这个类名
private static Logger log = LoggerFactory.getLogger(XXX.class);
第二个问题,我特别喜欢这种形式:
log.info("我在XXX 改了 {} 变量", "name");
既省去了可恶的isInfoEnabled()的判断,还避免了拼接字符串,但是呀
log.error("错误消息", e);
这样就不支持了,烦躁……
写多了就觉得这种厌烦的工作实在让人无法忍受,于是就封装了下。
Demo:
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import com.xiaoleilu.hutool.log.dialect.ApacheCommonsLogFactory;
import com.xiaoleilu.hutool.log.dialect.ConsoleLogFactory;
import com.xiaoleilu.hutool.log.dialect.JdkLogFactory;
import com.xiaoleilu.hutool.log.level.Level;
public class LogDemo {
public static void main(String[] args) {
Log log = LogFactory.get();
System.out.println("----------------------------自动选择日志------------------------------");
// 自动选择日志实现
log.debug("This is {} log", Level.DEBUG);
log.info("This is {} log", Level.INFO);
log.warn("This is {} log", Level.WARN);
log.error("This is {} log", Level.ERROR);
System.out.println("----------------------------自定义为Common Log日志------------------------------");
// 自定义日志实现
LogFactory.setCurrentLogFactory(new ApacheCommonsLogFactory());
log = LogFactory.get();
log.debug("This is {} log", Level.DEBUG);
log.info("This is {} log", Level.INFO);
log.warn("This is {} log", Level.WARN);
log.error("This is {} log", Level.ERROR);
System.out.println("----------------------------自定义为JDK Log日志------------------------------");
// 自定义日志实现
LogFactory.setCurrentLogFactory(new JdkLogFactory());
log = LogFactory.get();
log.debug("This is {} log", Level.DEBUG);
log.info("This is {} log", Level.INFO);
log.warn("This is {} log", Level.WARN);
log.error("This is {} log", Level.ERROR);
System.out.println("----------------------------自定义为Console Log日志------------------------------");
// 自定义日志实现
LogFactory.setCurrentLogFactory(new ConsoleLogFactory());
log = LogFactory.get();
log.debug("This is {} log", Level.DEBUG);
log.info("This is {} log", Level.INFO);
log.warn("This is {} log", Level.WARN);
log.error("This is {} log", Level.ERROR);
}
}
总结下来如果日志比较少,可以直接使用静态方法StaticLog.xxx,如果日志量很大,那么首先要构建好Logger,使用:
private static final Log log = LogFactotry.get();
log.debug("This is {} log", Level.DEBUG);
log.info("This is {} log", Level.INFO);
log.warn("This is {} log", Level.WARN);
log.error("This is {} log", Level.ERROR);
比之前简短了很多,而且随便复制。 调用log.xxx(log, "消息");
对于不能使用format的情况,我把Throwable放在前面了,这样就可以使用动态参数了 Object... argument
好吧,就到这里,欢迎批评指正以及提供意见~~~