Good logging practice

I am using sl4j / logback as a logging framework. I don't know how to log errors correctly. Namely, if e is the Exception I want to log, I always hesitate between:

  • logger.error("Something bad happened: {}\nError: {}", someInfo, e.getMessage());

    I understand that this is not a good practice because the stack trace is lost - it is not very good to understand what happened.

  • logger.error("Something bad happened: {}\nError: {}", someInfo, e.getMessage(), e);

    Using both e.getMessage()

    and e

    seems like overkill, although I don't know if it is possible that it e.getMessage()

    might contain additional information that would not be visible if I used:

  • logger.error("Something bad happened: {}", someInfo, e);

    which is the syntax I usually use, but I want to make sure I haven't missed anything.

+3


source to share


3 answers


I usually use number two, although I NEVER split one log line into two lines (\ n), although it doesn't really matter when printing a stack trace (in all other cases it creates too much visual entropy when your logs get really huge) ...

Why am I using number 2?

I want to see the message right away, on the first line, since that is the first thing that tells me what happened. Some may be expected and I can safely skip them, and some may not be.



In case I need to check what exactly happened, I better consider the stack trace.

I think number 3 is fine too, as you will get the information you need anyway. NEVER use parameter 1.

By the way, and only a specific opinion saying that something bad happened on the ERROR line is a little redundant;)

+2


source


If you look at the Throwable source code (http://www.docjar.com/html/api/java/lang/Throwable.java.html) you find that Throwable, when asked to print its stack, starts with an attraction which prints its message.



I find it unlikely that anyone will change this behavior, so your arguments are correct and the parameter 3. is excellent [/ p>

+1


source


You definitely want a stack trace. The message is useful in cases where you have done something like "Error: Could not find client with id: {0}", which may not be on the stack. A trivial example, but you know what I mean.

Another one for the post - if you are doing a log like csv says so you can parse it. You can standardize the message and make filtering easier.

Last but not least, the information contained in the error log is a way that is not a problem, and then information that you do not need. Err on the emergency verbosity side is my guiding principle.

Oh this is for controlled access to the log file, never say stack trace as a response in asp for example. Hackers wet dreams of that.

+1


source







All Articles