Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substituting parameters in log message and add a Throwable in Log4j 2

I am trying to log an exception, and would like to include another variable's value in the log message. Is there a Logger API that does this?

logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception); 
like image 236
derrdji Avatar asked Jan 30 '16 00:01

derrdji


People also ask

How do you change the log level in log4j 2?

You can set a logger's level with the class Configurator from Log4j Core. BUT be aware that the Configurator class is not part of the public API. If you wish to change the root logger level, do something like this : LoggerContext ctx = (LoggerContext) LogManager.

Does log4j throw exception?

In most cases exceptions will be handled within Log4j but certain Appenders may be configured to allow exceptions to propagate to the application. This is a RuntimeException so that the exception may be thrown in those cases without requiring all Logger methods be contained with try/catch blocks.

Does log4j call toString?

Next up is the actual format of the message. Using “{}” parameter markers causes Log4j to call toString() on each argument you pass to logger methods like debug(). There are 2147483647 users logged in now.


1 Answers

There is an undocumented feature in Log4j 2 (and SLF4J 1.6+). One can pass Throwable as the very last parameter. And it would then get a special treatment. See AbstractLogger#logMessage(String, Level, Marker, String, Object...) and ReusableParameterizedMessage#initThrowable().

There is no need to bother with ParametrizedMessage. The code in the question will work just as expected:

logger.error("Logging in user {} with birthday {}", user.getName(), user.getBirthdayCalendar(), exception);

like image 188
Dzmitry Avatar answered Sep 21 '22 13:09

Dzmitry