Niche
Niche

Reputation: 142

Which is the better way to write log statements

JAVA Logging:

Which is the better way to write log statements:
1. log.info("Value1 : {} Value2:{} Value3:{}",new Object[]{a,b,c};
Or
2. log.info(String.format("Value1 : %s Value2:%s Value3:%s",a,b,c));

Upvotes: 0

Views: 107

Answers (3)

Jeevan Varughese
Jeevan Varughese

Reputation: 2199

Better way to write is to pass the values into the logger. The logger's info() or debug() takes variable arguments. Assuming that you are using log4j or slj4j or logback as library. If you have not decided, seriously consider logback.

The right way to write will be as follows.

log.info("Value1 :{} Value2: {} Value3: {}", a, b, c);

You need not create a string object explicitly. This is handle internally by the logging framework.

If there is specific processing of the object just for logging, write logging after checking isDebugEnabled(), so in a production system, this will not be processed.

Upvotes: 0

wero
wero

Reputation: 32980

Prefer the first one.

If no log is written because your log level is higher than info then you have the cost of the call to log.info and the construction of the temporary parameter array. But the logger will not construct the log string.

In the second case you have the call plus the formatting of the log string which is likely more time consuming.

Upvotes: 0

gmaslowski
gmaslowski

Reputation: 764

There's no better or worse way. Both will give you the same output. However I suggest using slf4j (with logback provider for example). With such configuration you could log in this way:

log.info("{} {} {}", a, b, c);

Upvotes: 1

Related Questions