本文是在 SpringBoot 中使用,建立時選擇了 web 功能,所以不用額外導入slf4j-api 依賴
一、源碼分析
public class Test {
// 使用指定類初始化日誌對象
private static final Logger log = LoggerFactory.getLogger(Test.class);
}
LoggerFactory.getLogger
可以在 IDEA 控制檯打印日誌,便於開發,一般加在最上面
進入 getLogger
:
可以發現這裏返回來了一個以 name 命名的靜態綁定的實例
繼續進入 getILoggerFactory()
查看具體的返回:
public static ILoggerFactory getILoggerFactory() {
if (INITIALIZATION_STATE == 0) {
Class var0 = LoggerFactory.class;
synchronized(LoggerFactory.class) {
if (INITIALIZATION_STATE == 0) {
INITIALIZATION_STATE = 1;
performInitialization();
}
}
}
switch(INITIALIZATION_STATE) {
case 1:
return SUBST_FACTORY;
case 2:
throw new IllegalStateException("org.slf4j.LoggerFactory in failed state. Original exception was thrown EARLIER. See also http://www.slf4j.org/codes.html#unsuccessfulInit");
case 3:
return StaticLoggerBinder.getSingleton().getLoggerFactory();
case 4:
return NOP_FALLBACK_FACTORY;
default:
throw new IllegalStateException("Unreachable code");
}
}
發現這裏根據相應的參數返回相應的日誌信息
二、示例演示
public class Test {
private static final Logger log = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
File file = new File("D:\\flv\\GAN.pdf");
log.info("[文件名稱] - [{}]", file.getName());
log.info("[文件路徑] - [{}]", file.getAbsolutePath());
try {
int i = 10/0;
} catch (Exception e) {
log.info(e.getMessage());
}
}
}
slf4j 目前提供了 trace, debug, info, warn, error 5 種level
注意:
在打印日誌的時候,不要使用字符串拼接,要習慣使用佔位符
對於佔位符的形式而言,只有在我們需要的時候纔會提取字符串,這樣就會避免創建string對象的時候消耗大量的資源
因爲string
對象是不可變的,所以會消耗大量的堆內存,一旦我們用了字符串拼接,就有大量的字符串佔用機器的內存,但是當我們用佔位符的時候,只有在用到的時候纔會動態的創建