I want to log an error(with log4j 2) with some dynamic parameters that will provide better understanding what went wrong and I faced the problem that there is no method like:
void error(String message, Throwable t);
with parameters support.
In my code I want both exception and the parameters to fill {} in the message:
try {
//...
} catch (Exception e) {
LOGGER.error("Error removing data for account {}", accountId, e);
}
Is there a better way to implement it rather than using it like this?
LOGGER.error("Error removing token for account " + accountId, e);
Actually, almost all log4j logging methods that accept a message and arguments also accept a Throwable. Since the first release you have always been able to do:
logger.error("Error removing token for account {}", account, ex);
Notice that the format string only has one parameter so the throwable at the end is logged as an exception attached to the message. That is how the ParameterizedMessage class works.
In addition, support for LogBuilder was added in Log4j 2.13.0 which allows you to do
logger.atError().withException(ex).log("Error removing token for account {}", account);
which is a bit clearer. Note that all the following methods are called but if the error level is not being logged then all the methods following atError() are no-ops.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With