正如本教程前面所討論的,SLF4J提供了對參數化日誌消息的支持。可以在消息中使用參數,並在稍後的同一語句中將值傳遞給它們。
語法
如下所示,需要在消息(String)中的任何位置使用占位符({}
),稍後可以在對象形式中為占位符傳遞值,並使用逗號分隔消息和值。
Integer age;
Logger.info("At the age of {} I go to school.", age);
示例
以下示例演示使用SLF4J進行參數化日誌記錄(使用單個參數)。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
public static void main(String[] args) {
//Creating the Logger object
Logger logger = LoggerFactory.getLogger(PlaceHolders.class);
Integer age = 23;
//Logging the information
logger.info("At the age of {} I go to school.", age);
}
}
執行時,上述程式生成以下輸出 -
Dec 10, 2019 13:27:05 PM PlaceHolders main
INFO: At the age of 23 I go to school.
參數化日誌的優勢
在Java中,如果需要在語句中列印值,可使用連接運算符 -
System.out.println("At the age of "+23+" I go to school.");
這涉及將整數值:23
轉換為字串並將該值連接到其周圍的字串。
如果它是一個日誌記錄語句,並且如果語句的特定日誌級別被禁用,則所有這些計算都沒有用。
在這種情況下,可以使用參數化日誌記錄。在這種格式中,最初SLF4J確認是否啟用了特定級別的日誌記錄。如果是,那麼它將使用相應的值替換消息中的占位符。
例如,如果有一個語句為 -
Integer age;
Logger.debug("At the age of {} I go to school.", age);
只有在啟用了調試的情況下,SLF4J才會將age
轉換為整數並將其與字串連接,否則它什麼都不做。因此,禁用日誌記錄級別時會產生參數構造的成本。
兩個參數變體
還可以在消息中使用兩個參數 -
logger.info("Old weight is {}. new weight is {}.", oldWeight, newWeight);
以下示例演示了參數化日誌記錄中兩個占位符的用法。
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
public static void main(String[] args) {
Integer oldWeight;
Integer newWeight;
Scanner sc = new Scanner(System.in);
System.out.println("Enter old weight:");
oldWeight = sc.nextInt();
System.out.println("Enter new weight:");
newWeight = sc.nextInt();
//Creating the Logger object
Logger logger = LoggerFactory.getLogger(Sample.class);
//Logging the information
logger.info("Old weight is {}. new weight is {}.", oldWeight, newWeight);
//Logging the information
logger.info("After the program weight reduced is: "+(oldWeight-newWeight));
}
}
執行上面示例代碼,得到以下結果:
Enter old weight:
86
Enter new weight:
77
Dec 20, 2019 4:12:21 PM PlaceHolders main
INFO: Old weight is 86. new weight is 77.
Dec 20, 2019 4:12:21 PM PlaceHolders main
INFO: After the program weight reduced is: 9
多個參數變體
還可以使用兩個以上的占位符,如以下示例所示 -
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
public static void main(String[] args) {
Integer age = 23;
String designation = "Software Engineer";
String company = "zaixian";
//Creating the Logger object
Logger logger = LoggerFactory.getLogger(Sample.class);
//Logging the information
logger.info("At the age of {} Maxsu got his first job as a {} at {}", age, designation, company);
}
}
執行上面示例代碼,得到以下結果:
Dec 10, 2019 8:43:52 PM main
INFO: At the age of 23 I got his first job as a Software Engineer at zaixian
上一篇:
SLF4J錯誤消息
下一篇:
SLF4J遷移器(Migrator)