Java Logging exceptions, use getMessage or toString : log.warn(ex.getMessage()) or log.warn(ex) working with open source


My question is: it better to log with getMessage or with toString or both? taking in to account errors thrown by open source. Saw the questions in the comments but did not get an answer to this. Maybe I missed something ? Do not mind the small performance hit of logging one of them, but do not want to log both unless there is a good reason.

Meaning log(ex) or log(ex.getMessage), Not talking about stack trace.

Saw 1 , 2 and 3

Logging exceptions : which is better:
log.warn(ex.getMessage(), ex) or log.warn(ex, ex);

I noticed sometimes getMessage returns empty or null, so in general practice is there any reason not to use :

log.warn(ex, ex);

As it seems to print the class name and the message (if set) ? I guess one reason could be if a sub class has over ridden to string not to print the message, but in reality do any of the hibernate, apache or spring libs do that?

Best Solution

How about

log.warn("some descriptive message, maybe with context {}", 
    someId, ex);

The exception details will already be printed as part of the stacktrace, so you don't need to include them in the message usually.

In case you want to suppress the stacktrace and only print the exception message, usually, ex.toString() works better than ex.getMessage(), because it also includes the exception class name, which the message does not. In fact, often the message is empty (for example with NullPointerExceptions).