Differences between error methods in log4j 1.x

In the logging part of the project I working for, I try to optimize the error messages that are shown in log management. Logging error messages is coded like this:

String errorMessage =" Problem with server "+"\n"+t.getMessage();
_logger.fatal(errorMessage);

Where t is a Throwable object and _logger is a Logger object, which is related to the log4j framework.

What I wonder is, what changes if I use _logger.fatal(errorMessage, t); instead of _logger.fatal(errorMessage);? If there is a major difference between them, Which one will be better to use?

Edit: I've just realised I copied "fatal" example instead of "error". However my question is same for fatal, too.

1 answer

  • answered 2018-11-14 12:21 Thilo

    Practically all Java logging framework (alas, we have plenty of those...) support putting a Throwable as the last parameter.

    This will result in a stack trace being logged, which can be extremely useful in diagnosing and fixing the problem.

    I'd only ever not give the exception to the logger if the cause of the exception is really well established and printing the exception is just unnecessary noise. For example here:

    try {
       int port = Integer.parseInt(input);
       // do something with the port
    } catch (NumberFormatException e) {
       logger.error("'{}' is not a valid port number: {}", input, e.toString);
    }
    

    Another case is when the exception is being re-thrown (and something else will eventually log it with more detail).

    But not with a "Problem with server" (and at FATAL level no less). That looks like you want to get as much info as you can get.

    Also note that in those cases, e.toString() is usually better than e.getMessage() because it also includes the name of the exception in addition to its message (which may be empty).