I have a (probably) weird question about logging in an exception-safe way in java.
Let's say I have this code in java:
if (log.isDebugEnabled())
{
log.debug(...expression...);
}
Is there a best practice for logging ...expression..
in a way that any exception during evaluation doesn't make my application fail?
For example, I'd like this code to not break my application:
if (log.isDebugEnabled())
{
log.debug("a divided by b is " + (a/b)); // throws an exception if b is zero
}
I can obviously write my own wrapper that uses a lambda function (something like wrapperLog.debug(()->"a divided by b is " + (a/b)); but I'd like to know if there is a best practice for these kind of situations.
To be safe don't log expressions or the result of a method call. Log plain variables only: primitive types or bean types with a
toString()
generated by your IDE; in the latter case don't calltoString()
explicitly.