It’s not clear when the SLF4J API will catch up, but the Java 8 core API allows to defer any potentially expensive calculation to the point after the logging level has been checked, so it does not happen if the particular level is not loggable:
import java.util.logging.Logger; public class LogAbbr { final static int LIMIT = 15; public static void main(String[] args) { Logger log=Logger.getAnonymousLogger(); String[] examples={"short string", "rather long string"}; for(String responseContent: examples) { log.info(() -> String.format("RESPONSE: %."+LIMIT+"s%s", responseContent, responseContent.length()<=LIMIT? "": "...")); } } }
Note that when LIMIT is a compile-time constant, "RESPONSE: %."+LIMIT+"s%s" is a compile-time constant too, hence, there is no need to manually inline the number, so using a named constant ensures consistency between the formatting string and the conditional.
Demo on Ideone:
Jan 27, 2017 11:53:20 AM Ideone main INFO: RESPONSE: short string Jan 27, 2017 11:53:20 AM Ideone main INFO: RESPONSE: rather long str...
The following program demonstrates that the calculation does not happen, once the log level forbids it:
Logger log=Logger.getAnonymousLogger(); String[] examples={"short string", "rather long string"}; for(String responseContent: examples) { log.info(() -> { System.out.println("Potentially expensive operation with "+responseContent); return responseContent; }); log.setLevel(Level.SEVERE); }
Demo on Ideone:
tracemethod in the core Java logger and{}is not supported by the standard formatter.{}in the question.