Reputation: 328598
I use sl4j / logback as a logging framework. I am unsure about the right way to log errors. Namely, assuming e is an Exception I want to log, I always hesitate between:
logger.error("Something bad happened: {}\nError: {}", someInfo, e.getMessage());
I understand this is not good practice because the stack trace is lost - not great to understand what happened.
logger.error("Something bad happened: {}\nError: {}", someInfo, e.getMessage(), e);
Using both e.getMessage()
and e
seems redundant, although I don't know if it is possible that e.getMessage()
might contain extra information that would not be seen if I used:
logger.error("Something bad happened: {}", someInfo, e);
which is the syntax I generally use - but I want to make sure I am not missing anything.
Upvotes: 3
Views: 509
Reputation: 20320
You definitely want the stack trace. Message is handy in circumstances where you've done something like "Error : Unable to find customer with ID : {0}", which may not be in the stacktrace. Trivial example but you get what I mean.
Another one for message is if you do the log as say a csv so you can analyse it. You can standarise message, and make filtering easier.
Last but not least redundant info in an error log, is way way way less of a problem, then the info you need not being in it. Err on the side of extreme verbosity is my guiding principle.
Oh this is for contrrolled access to a log file ,never say put stack trace as a response in asp for instance. Hackers wet dream that.
Upvotes: 1
Reputation: 81862
If you look at the source code of Throwable (http://www.docjar.com/html/api/java/lang/Throwable.java.html) you'll find that a Throwable when asked to print its stacktrace starts by priting itself, which prints its message.
I find it unlikely that anybody would change this behaviour, so your arguments are all correct and the 3. option is fine
Upvotes: 1
Reputation: 15975
I usually use number two, although I NEVER break one line of log into 2 lines (\n), although when printing the stack trace, it won't matter much (in all other cases, it creates too much visual entropy when your logs become really huge).
Why do I use number 2?
I want to see the message right away, on the first line, since it's the first thing that tells me what happened. Some might be expected and I can safely skip them, and some might not be.
In case I need to examine exactly what happened, I take a better look at the stack trace.
I reckon number 3 is also fine, since you'll get the information you need anyway. NEVER use option 1.
By the way, and just a particular opinion, saying that something bad happened on a ERROR line is a bit redundant ;)
Upvotes: 2