-1

Anybody an idea how I include the delimiter for the thousand power in big numbers using the {} annotation?

log.info("Reading {} entries (multiplied with one million)", entries * 1_000_000);

Output (currently):

Reading 80000000 entries (multiplied with one million)

Output (desired):

Reading 80,000,000 entries (multiplied with one million)

Is there a way to realize this directly in Log4J2 without using an additional formatter like e.g. DecimalFormat?

1 Answers1

1

When you call one of the logger methods, Log4j2 creates a Message, which usually has a fixed string representation.

Most methods create ParameterizedMessages (cf. available messages), that use StringBuilder#append to format your parameters. This does not provide any alternative representation for integers.

If you want a different format you can:

  1. Use Logger#printf which interprets your format string using java.util.Formatter and creates a StringFormattedMessage:

    log.printf(Level.INFO, "Reading %,d entries (multiplied with one million)",
            entries * 1_000_000);
    

    As you can deduce from the method signature, it always creates a temporary object array and is not garbage-free.

  2. When you create your logger, you can specify a different MessageFactory. If you use StringFormatterMessageFactory, all your messages will be formatted with java.util.Formatter:

    final Logger log = LogManager.getLogger(MyClass.class,
            StringFormatterMessageFactory.INSTANCE);
    log.info("Reading %,d entries (multiplied with one million)", entries * 1_000_000);
    

    This solution does not create temporary object arrays.

  3. You can also use FormattedMessageFactory, which dynamically determines if your format string conforms to java.util.Formatter, java.text.MessageFormat or uses simple {} placeholders. This flexibility, of course, comes at a slight performance cost.

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43