I am using Log4j2 for logging. Multiple operations return success code. If status 0
is received, it means operation is successful, else failed. If operation is successfully, I log "*** is successfully."
and if it fails I logs "*** failed with status : " + status
. This is kind of repetitive in code.
public class ReadCallbackManager {
//Log Object
private static final Logger LOGGER = LogManager.getLogger(ReadCallbackManager.class);
private static ReadCallback readCallback;
private static final int SUCCESS_STATUS = 0;
public int setHook(final ICallback aCallBack) {
readCallback = new ReadCallback(aCallBack);
final int status = readCallback.setHook();
if (status == SUCCESS_STATUS) {
LOGGER.info("Read callback hook is set successfully!!!");
} else {
LOGGER.info("Read Callback hook set failed with status : " + status);
}
return status;
}
}
So I though to create a wrapper around the Logger class to handle this if else condition as below:
public final class BacStacLogger {
public static final int SUCCESS_STATUS = 0;
//Log Object
private Logger logger;
public BacStacLogger(final Class<?> className) {
if (logger == null) {
logger = LogManager.getLogger(className);
}
}
public void infoHookByStatus(final int status, final String successMessage, final String failureMessage) {
if (status == SUCCESS_STATUS) {
logger.info(successMessage);
} else {
logger.info(failureMessage + " : " + status);
}
}
}
And I have updated my previous code as :
public class ReadCallbackManager {
//Log Object
private static final ProjectLogger LOGGER = ProjectLogger(ReadCallbackManager.class);
private static ReadCallback readCallback;
public int setHook(final ICallback aCallBack) {
readCallback = new ReadCallback(aCallBack);
final int status = readCallback.setHook();
LOGGER.infoHookByStatus(status, "Read hook set successfully.", "Read hook set failed.");
return status;
}
}
Would you please provide your comments on it? Or if required, any improvements?
if
statement with a lot more code. If it is not a matter of relevance may be consider logging thestatus
directlyLOGGER.info("Read callback hook response " + status);
On the encapsulation itself, I think that is a good solution if you anticipate future uses, for now I'd keep it simple. \$\endgroup\$LOGGER
, indicating that you consider it to be a constant. According to the Google Java Style Guide: "Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. (...)" ALogger
object has a side effect and is therefore not a constant. Source - with logger as an explicit example \$\endgroup\$logger.info("Read callback hook response: {}, success: {}", status, status == SUCCESS_STATUS)
\$\endgroup\$