Class MyComplexClass{
// No override of toString() here
}
…
log.debug(“Something happened here{}”, myObject.toString())
Other than the redundancy of the toString() here, is it possible if the log level is changed, the cost of toString() is still incurred?
Yes, the cost is still incurred.
No matter which log level is used, the code always calls myObject.toString()
before log.debug is called.
This:
log.debug("Something happened here {}", myObject.toString());
is exactly the same as this:
String s = myObject.toString();
log.debug("Something happened here {}", s);
As you can see, the toString() call happens every single time. It is not under the control of the logger at all.
The way to be sure the cost of toString is only incurred when the corresponding log level is active is to avoid calling toString, and let the logger library’s own code call toString if and only if such a call is needed:
// Notice there is no visible toString call!
log.debug("Something happened here {}", myObject);