I went through the logging in my application and found that a lot of it was very messy because I used StringBuilders with appends and guard clauses to check whether or not to build the string.
ie
StringBuilder globalSB = new StringBuilder();
//random other code
//place that needs to be logged
globalSB.setLength(0);
globalSB.append("something").append("other something").().().().append("end"); //<--imagine theres a lot of appending of variables/objects etc
LOGGER.info(globalSB.toString());
I recently came across this question and answer that suggests to use parameterized logging, though its not clear if its slf4j or log4j. Many other answers suggest to directly use slf4j,since it will check if the string concatenation needs to happen (logging level) before actually building the string; or to just directly use guard clauses regardless since the overhead of checking the debug level is insignificant.
I m kinda looking to find out what log4j2 can do instead of what slf4j can do, so I checked some other question/answer/comments and found that some suggest the newer versions of log4j2 support behavior similar to that of slf4j and the lazy(?) string building (using parameterized logging) as well as Java 8 lambda support for lazy logging. ie 1, 2.
Is it mandatory to use guard clauses (then use a stringbuilder etc), or does parameterized logging with lambdas for expensive method calls also provide same behavior (does not create the string unless log level dictates it is needed)? I m hoping to get an answer, because many of the other posts seems to have divided opinions. ie
byte[] rawIp; //assume it has some value
int port; //assume it has some value
String msgReceived;//assume it has some value
LOGGER.debug("{},{} sent {}", ()->rawIp.convertToString(), port, msgReceived);