Richard
Richard

Reputation: 6116

Java logback nested variable substitution

I have a logging statement like so:

private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);

long elapsedTime = 8348; //test value
LOGGER.info("message:{},timestamp:{}",
                "Finished execution in {} milliseconds", elapsedTime,
                LocalDateTime.now());

I want the first 2 {} to be replaced by the string message and the localdatetime. But the third {} inside the message should be replaced by the long. So it should log:

INFO  app.Foo - message:Finished execution in 8348 milliseconds,timestamp:2016-03-25T13:55:05.026

But instead it logs:

INFO  app.Foo - message:Finished execution in {} milliseconds,timestamp:5017

Any way to have nested variable substitution for logging? I could concatenate the strings like so

long elapsedTime = 8348; //test value
LOGGER.info("message:{},timestamp:{}",
                "Finished execution in " + elapsedTime + " milliseconds",
                LocalDateTime.now());

But I want to avoid tediously concatenating.

Upvotes: 0

Views: 825

Answers (2)

Bhushan Bhangale
Bhushan Bhangale

Reputation: 10987

It will not work that way as the message value is simply replaced and not parsed. The var arg parameters are for the main message format.

I can think of following two options.

LOGGER.info("message:Finished execution in {} milliseconds,timestamp:{}", elapsedTime,
 LocalDateTime.now());

OR

LOGGER.info("message:{},timestamp:{}", String.format("Finished execution in %s milliseconds",
 elapsedTime), LocalDateTime.now());

Upvotes: 1

Dennis R
Dennis R

Reputation: 1937

I checked Logback 1.1.5

ch.qos.logback.classic.spi.LoggingEvent

and argumentArray in it. And

org.slf4j.helpers.MessageFormatter.arrayFormat

Nesting is not supported, only array of objects in additional arguments. I think the same applies to Log4j.

Upvotes: 0

Related Questions