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()andeseems redundant, although I don’t know if it is possible thate.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.
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 😉