Home > database >  What is the difference between LOGGER.error(exception.getMessage()) and LOGGER.error(exception.getMe
What is the difference between LOGGER.error(exception.getMessage()) and LOGGER.error(exception.getMe

Time:02-11

Like in this picture

I know that both of them works fine but I just wanted to know how are they different from each other? PS: I am a beginner.

CodePudding user response:

From the docs:

error(String message)

Logs a message object with the ERROR level.

error(String message, Throwable throwable)

Logs a message at the ERROR level including the stack trace of the Throwable throwable passed as parameter.

CodePudding user response:

A LogEvent can contain both a message and an exception. If you use the first form:

LOGGER.error(exception.getMessage());

only the error message will be recorded and you'll have a similar output in your logs (depends upon the layout):

[ERROR] - Exception message.

If you use the second form:

LOGGER.error(exception.getMessage(), exception);

you'll have both a message and an exception. This typically outputs the stack trace in the logs:

[ERROR] - Exception message.
java.lang.RuntimeException: Exception message.
    at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
    at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]

Since you can always configure Log4j 2.x to suppress stack traces from the output (see alwaysWriteExceptions in the PatternLayout documentation), the second form is always better, as it provides more information.

Remark: Since the stack trace always prints the error's message, I'd suggest a third form:

LOGGER.error("An unexpected condition occurred while performing foo: {}",
    exception.getMessage(), exception);

This way you can explain the context, when the exception occurred:

[ERROR] - An unexpected condition occurred while performing foo: Exception message.
java.lang.RuntimeException: Exception message.
    at pl.copernik.log4j.Log4j2Test.run(Log4j2Test.java:19) [classes/:?]
    at pl.copernik.log4j.Log4j2Test.main(Log4j2Test.java:15) [classes/:?]
  • Related