日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码

發(fā)布時間:2025/3/20 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

如下是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模式的典型應(yīng)用,它定義了一套標(biāo)準(zhǔn)的日志接口,諸如logback、log4j、slf4j-simple等框架都是這個日志接口的具體實現(xiàn)。從這一點(diǎn)來看,slf4j的標(biāo)準(zhǔn)化顯得相當(dāng)重要,當(dāng)然,從上面這些方法可見,它做到了!

我這里要點(diǎn)贊的也是這幾個方法的定義。注意觀察比較這幾個有參的info/error方法的第一個參數(shù):有的是format,有的是msg。

充分展現(xiàn)了代碼的整潔之道,由此可以看出來作者是很講究代碼的可讀性的。

看上面幾個方法,

  • 如果記錄異常信息,不妨調(diào)用error(String msg, Throwable t)方法。這時,第一個參數(shù)不是format,是msg。所以下面語句里的“{}”就有畫蛇添足之嫌了:
try {......} } catch (IOException e) {LOG.error("#PayCenterHttpTransport,http調(diào)用出錯!異常信息:{}", e); }
  • 如果要打印更詳細(xì)的info日志,可以調(diào)用logger.info那幾個重載方法,支持用format形式。
log.info("融寶請求url:{},請求報文:{}", url, json);
  • logger.error也是支持format的。如下是Logger接口類里這個error重載方法的定義。注意調(diào)用方式是 log.error("執(zhí)行請求{}出現(xiàn)異常,",1,new Exception("test"));
/*** Log a message at the ERROR level according to the specified format and arguments.* <p/>* <p>This form avoids superfluous object creation when the logger is disabled for the ERROR level. </p>** @param format the format string* @param arg1 the first argument* @param arg2 the second argument*/public void error(String format, Object arg1, Object arg2);

?

打印的異常日志是:

14:55:25.997 [main] ERROR ddd - 執(zhí)行請求1出現(xiàn)異常, java.lang.Exception: testat com.emax.paycenter.common.util.MailUtil.main(MailUtil.java:100) [classes/:na]

?

?

=====over=====

轉(zhuǎn)載于:https://www.cnblogs.com/buguge/p/8526868.html

總結(jié)

以上是生活随笔為你收集整理的强迫症犯了,忍不住赞一下slf4j包Logger.java的优雅代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。