SLF4J - 引數化日誌記錄



如本教程前面所述,SLF4J 支援引數化日誌訊息。

您可以在訊息中使用引數,並在稍後的同一語句中傳遞值。

語法

如下所示,您需要在訊息(字串)中使用佔位符({}),稍後您可以以**物件**形式傳遞佔位符的值,並用逗號分隔訊息和值。

Integer age;
Logger.info("At the age of {} ramu got his first job", 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 {} ramu got his first job", age);
   }
}

輸出

執行後,上述程式生成以下輸出:

Dec 10, 2018 3:25:45 PM PlaceHolders main
INFO: At the age of 23 Ramu got his first job

引數化日誌記錄的優勢

在 Java 中,如果我們需要在語句中列印值,我們將使用連線運算子,如下所示:

System.out.println("At the age of "+23+" ramu got his first job");

這涉及將整數 23 轉換為字串,並將該值與周圍的字串連線起來。

如果這是一個日誌語句,並且該語句的特定日誌級別被停用,那麼所有這些計算都將毫無用處。

在這種情況下,您可以使用引數化日誌記錄。在此格式中,SLF4J 最初會確認是否啟用了特定級別的日誌記錄。如果是,則它會將訊息中的佔位符替換為相應的值。

例如,如果我們有一個語句如下:

Integer age;
Logger.debug("At the age of {} ramu got his first job", 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:
85
Enter new weight:
74
Dec 10, 2018 4:12:31 PM PlaceHolders main
INFO: Old weight is 85. new weight is 74.
Dec 10, 2018 4:12:31 PM PlaceHolders main
INFO: After the program weight reduced is: 11

多個引數變體

您還可以使用兩個以上的佔位符,如下例所示:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
   public static void main(String[] args) {
      Integer age = 24;
      String designation = "Software Engineer";
      String company = "Infosys";

      //Creating the Logger object
      Logger logger = LoggerFactory.getLogger(Sample.class);

      //Logging the information
      logger.info("At the age of {} ramu got his first job as a {} at {}", age, designation, company);
   }
}

輸出

執行後,上述程式生成以下輸出:

Dec 10, 2018 4:23:52 PM PlaceHolders main
INFO: At the age of 24 ramu got his first job as a Software Engineer at Infosys
廣告