强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码
生活随笔
收集整理的這篇文章主要介紹了
强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如下是slf4j-api包下的Logger接口類里其中幾個方法的聲明:
package org.slf4j;public interface Logger {/*** Log a message at the INFO level.** @param msg the message string to be logged*/public void info(String msg);/*** Log a message at the INFO level according to the specified format and argument.** @param format the format string* @param arg the argument*/public void info(String format, Object arg);/*** Log a message at the INFO level according to the specified format and arguments.** @param format the format string* @param arguments a list of 3 or more arguments*/public void info(String format, Object... arguments);/*** Log a message at the ERROR level.** @param msg the message string to be logged*/public void error(String msg);public void error(String format, Object arg);public void error(String format, Object... arguments);/*** Log an exception (throwable) at the ERROR level with an accompanying message.** @param msg the message accompanying the exception* @param t the exception (throwable) to log*/public void error(String msg, Throwable t); }?
slf4j(Simple Logging Facade for Java)是Facade模式的典型應用,它定義了一套標準的日志接口,諸如logback、log4j、slf4j-simple等框架都是這個日志接口的具體實現。從這一點來看,slf4j的標準化顯得相當重要,當然,從上面這些方法可見,它做到了!
我這里要點贊的也是這幾個方法的定義。注意觀察比較這幾個有參的info/error方法的第一個參數:有的是format,有的是msg。
充分展現了代碼的整潔之道,由此可以看出來作者是很講究代碼的可讀性的。
看上面幾個方法,
- 如果記錄異常信息,不妨調用error(String msg, Throwable t)方法。這時,第一個參數不是format,是msg。所以下面語句里的“{}”就有畫蛇添足之嫌了:
- 如果要打印更詳細的info日志,可以調用logger.info那幾個重載方法,支持用format形式。
- logger.error也是支持format的。如下是Logger接口類里這個error重載方法的定義。注意調用方式是 log.error("執行請求{}出現異常,",1,new Exception("test"));
?
打印的異常日志是:
14:55:25.997 [main] ERROR ddd - 執行請求1出現異常, java.lang.Exception: testat com.emax.paycenter.common.util.MailUtil.main(MailUtil.java:100) [classes/:na]?
?
=====over=====
轉載于:https://www.cnblogs.com/buguge/p/8526868.html
總結
以上是生活随笔為你收集整理的强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzoj 4921: [Lydsy六月月
- 下一篇: 在 .NET Framework 4.0