I have the following code. The log level is INFO. How can we write the better code that the toString will not be executed ?
Set<Integer> resultUserIdsSet = new HashSet<>();
log.trace("userIdsSet={}", resultUserIdsSet.toString());
Note: The resultUserIdsSet contains milions of integers.
We use ch.qos.logback:logback-classic:jar:1.2.3
Everyone is telling you to use a Supplier, but there is no need for that. Just let the logger do the toString call:
log.trace("userIdsSet={}", resultUserIdsSet);
By removing .toString()
, you are just passing a reference to the Set. If the trace level is not enabled, the logger call returns immediately; the cost is essentially negligible.
If and only if the trace level is enabled, then the logger will invoke toString()
on the Set.