Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
tgkprog Avatar asked Feb 02 '15 06:02

tgkprog


People also ask

What is exception getMessage ()?

The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value. Syntax: public String getMessage()

What are exceptions used for in Java?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

What does exception ToString return?

ToString returns a representation of the current exception that is intended to be understood by humans. Where the exception contains culture-sensitive data, the string representation returned by ToString is required to take into account the current system culture.

Can we show default exceptions to user?

No, exceptions shouldn't be shown directly in error messages directly to the user, they're low level technical details and the user almost always wants something more understandable, even if it doesn't provide as much information as a stack trace would!


1 Answers

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

like image 107
Thilo Avatar answered Oct 19 '22 05:10

Thilo