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);
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.
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.
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.
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);
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