javaspringlog4j2apache-commonsjava.util.logging

What is the difference between LOGGER.error(exception.getMessage()) and LOGGER.error(exception.getMessage(), exception)


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.

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

picture of code


Solution

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

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

    [ERROR] - An unexpected condition occurred while performing foo.
    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/:?]