Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using throwable along with parameters in log4j 2 [duplicate]

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);
like image 246
dvelopp Avatar asked Aug 06 '18 10:08

dvelopp


1 Answers

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.

like image 86
rgoers Avatar answered Oct 03 '22 08:10

rgoers