Home > Back-end >  Exception Standard for different logging levels
Exception Standard for different logging levels

Time:09-18

Which is more suitable out of these two exception object (e) or e.getMessage() for log.info() and log.error() or log.debug().

What should be followed/rule of thumb for different logging levels.

CodePudding user response:

It really depends on the reason of the exception being thrown. I would add here WARN level consideration as well. If this is an unexpected error that should not happen, meaning that this is something wrong with codebase you should definitely log the whole exception object, especially to get the stacktrace that allow developer to find and potentially fix issue faster. Therefore such situation should be logger on ERROR level if this is something wrong with the system, or WARN if this is something wrong with client's data.

INFO level should really not contain exception details, it should keep information easy to read by non-developers(for example testers) and describe the most important parts of the data processing flow.

I think it is up to you to put exception in DEBUG level but I would still recommend not to do it just to keep things clearer OR use e.getMessage() to describe it.

P.S. In general, I would redirect this question to this page since it is a general SE question but since you asked about using particular Java feature I wanted to keep things in the right place.

CodePudding user response:

Don't try to create a fixed rule about including or not including the stacktrace depending on the log level. Instead, when creating a log entry, ask yourself:

  • Who will read that entry? A user, a system administrator, or a developer?
  • What information will be useful to that reader for understanding the situation? It's better to add too much information than to omit important parts.
  • If the entry is to be read by a developer, is the text enough or should I include the stacktrace? Non-developers typically get confused when seeing a stacktrace, but developers very much appreciate it.

This will greatly improve the quality of your logging.

As a very rough rule of thumb, include the stacktrace whenever you log an exception. An exception means that something went wrong, which might involve analysis by a developer, who will be very unhappy if the log entry only reads "NullPointerException" without a hint where it came from.

Of the typical log levels, INFO might be the one not addressing developers (thus not asking for a stacktrace), but generally you don't want to use INFO for exceptions.

  • Related