📜  SLF4J-参数化日志记录

📅  最后修改于: 2020-11-11 05:12:44             🧑  作者: Mango


如本教程前面所述,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才将年龄转换为整数并将其与字符串连接,否则,它将不执行任何操作。因此,在禁用日志记录级别时会产生参数构造的开销。

两种说法的变体

您还可以在消息中使用两个参数,如-

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