正如本教學前面所討論的,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 = "Yiibai";
//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 Yiibai