Vinny Gray
Vinny Gray

Reputation: 547

What are the formatting pattern semantics in Java Util Logging?

I am trying to make sense of the formatting patterns used in Java Util Logging. Just by experiment I see the following:

%1$ts     epoch time: 1657069724
%1$tc     Standard date/time format: Tue Jul 05 20:59:21 EDT 2022
%1$tY     year - 2022
%1$tb     3 char month - Jul
%1$th     3 char month - Jul
%1$tm     2 digit month - 07
%1$td     2 digit day of month - 05
%1$tH:    hours (0-23) 21:
%1$tM:    minutes: 03:
%1$tS.    Seconds: 55.
%1$tL     Milleseconds 294
%2$s      logger name and method
%3$s      logger name
%4$-7s    log level of this message - WARNING

(the -7 before the s means left justify in a 7 character field. Remove the "-" to right justify)

Are these documented anywhere? I do not see anything in the SimpleFormat API or in Java Util Logging docs

Upvotes: 4

Views: 3717

Answers (1)

jmehrens
jmehrens

Reputation: 11045

java.util.logging.SimpleFormatter::format explains this:

The formatting can be customized by specifying the format string in the java.util.logging.SimpleFormatter.format property. The given LogRecord will be formatted as if by calling:

String.format(format, date, source, logger, level, message, thrown);

where the arguments are:

  1. format - the java.util.Formatter format string specified in the java.util.logging.SimpleFormatter.format property or the default format.
  2. date - a ZonedDateTime object representing event time of the log record in the ZoneId.systemDefault() system time zone.
  3. source - a string representing the caller, if available; otherwise, the logger's name.
  4. logger - the logger's name.
  5. level - the log level.
  6. message - the formatted log message returned from the Formatter.formatMessage(LogRecord) method. It uses java.text formatting and does not use the java.util.Formatter format argument.
  7. thrown - a string representing the throwable associated with the log record and its backtrace beginning with a newline character, if any; otherwise, an empty string.

Note that the %[argument_index$] is off by one from the javadocs in SimpleFormatter as format is listed as the argument number one. E.G. date is listed as 2 but is really %1$.

String::format has a "see" reference to java.util.Formatter (not to be confused with java.util.logging.Formatter).

The class level documentation of `java.util.Formatter' includes information on 'Date/Time Conversions' and 'Flags'.

If you use parameterized logging you can also do some formatting with java.text.MessageFormat on the parameters of a LogRecord. This can be used to change the behavior of the 'message' parameter passed to String::format.

Upvotes: 3

Related Questions