模块 java.logging

类 SimpleFormatter

java.lang.Object
java.util.logging.Formatter
java.util.logging.SimpleFormatter

public class SimpleFormatter extends Formatter
以人类可读的格式打印 LogRecord 的简短摘要。摘要通常为 1 或 2 行。

配置: SimpleFormatter 使用在 java.util.logging.SimpleFormatter.format 属性中指定的格式字符串初始化为 format 日志消息。此属性可以在记录属性 配置文件中定义或作为系统属性。如果在日志记录属性和系统属性中都设置了此属性,则将使用系统属性中指定的格式字符串。如果未定义此属性或给定格式字符串为 非法的 ,则默认格式是特定于实现的。

自从:
1.4
参见:
  • 构造方法详细信息

    • SimpleFormatter

      public SimpleFormatter()
      创建一个 SimpleFormatter
  • 方法详情

    • format

      public String  format(LogRecord  record)
      格式化给定的 LogRecord。

      可以通过在 java.util.logging.SimpleFormatter.format 属性中指定格式字符串来自定义格式。给定的 LogRecord 将被格式化为好像通过调用:

        String.format (format, date, source, logger, level, message, thrown);
       
      其中参数是:
      1. format - 在 java.util.logging.SimpleFormatter.format 属性中指定的 java.util.Formatter 格式字符串或默认格式。
      2. date - ZonedDateTime 对象表示 ZoneId.systemDefault() 系统时区中日志记录的 活动时间
      3. source - 表示调用者的字符串(如果可用);否则,记录器的名称。
      4. logger - 记录器的名称。
      5. level - 日志级别
      6. message - 从 Formatter.formatMessage(LogRecord) 方法返回的格式化日志消息。它使用 java.text 格式,不使用 java.util.Formatter format 参数。
      7. thrown - 表示与日志记录相关联的 可抛 的字符串及其以换行符开头的回溯,如果有的话;否则为空字符串。

      一些示例格式:

      • java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"

        这将打印 1 行,日志级别 (4$)、日志消息 (5$) 和方括号中的时间戳 (1$)。

           WARNING: warning message [Tue Mar 22 13:11:31 PDT 2011]
           
      • java.util.logging.SimpleFormatter.format="%1$tc %2$s%n%4$s: %5$s%6$s%n"

        这将打印 2 行,其中第一行包括时间戳 (1$) 和源代码 (2$);第二行包括日志级别(4$)和日志消息(5$),然后是可抛出对象及其回溯(6$),如果有的话:

           Tue Mar 22 13:11:31 PDT 2011 MyClass fatal
           SEVERE: several message with an exception
           java.lang.IllegalArgumentException: invalid argument
               at MyClass.mash(MyClass.java:9)
               at MyClass.crunch(MyClass.java:6)
               at MyClass.main(MyClass.java:3)
           
      • java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%n"

        这会打印 2 行,类似于上面的示例,但具有不同的日期/时间格式,并且不会打印 throwable 及其回溯:

           Mar 22, 2011 1:11:31 PM MyClass fatal
           SEVERE: several message with an exception
           
      • java.util.logging.SimpleFormatter.format="%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS.%1$tN %1$Tp %2$s%n%4$s: %5$s%6$s%n"

        从 JDK 9 开始,java.util.logging 使用 java.time 创建更精确的时间戳。上面的格式可用于将 .%1$tN 添加到日期/时间格式,以便也将打印纳秒:

           Feb 06, 2015 5:33:10.279216000 PM example.Main main
           INFO: This is a test
           

      这个方法也可以在子类中被覆盖。建议使用 Formatter.formatMessage(java.util.logging.LogRecord) 便捷方法对消息字段进行本地化和格式化。

      指定者:
      format 在类 Formatter
      参数:
      record - 要格式化的日志记录。
      返回:
      格式化的日志记录