0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rossomoto
  • 9
  • 1
  • There is pretty much no such thing as "best practice". People have different opinions about things, especially programmers. – Michael Apr 05 '23 at 15:18

1 Answers1

3

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 call toString() explicitly.

Pino
  • 7,468
  • 6
  • 50
  • 69
  • 1
    I was about to write the same. I think logging generally should be simple enough that there should be no need for exception handling. – kapex Apr 05 '23 at 15:35
  • Unfortunately, on the projects I work on, this approach is not feasible: there already is a lot of suboptimal code and management mandate the preference. of fast development over quality one, so "doing things the right way" is not a policy I can enforce.

    Also, even if I were able to, I wouln't be able to enforce that policy in the future, when other (usually less experienced people) will take over the code

    So my problem is not "how to do logging correctly" (that is out of the question). My problem is "how to do logging without the logging breaking the application".
    – Rossomoto Apr 05 '23 at 19:29
  • So the question is: "I know that my code is poor, how can I make it exception-safe without changing it?". Sorry, no solution. – Pino Apr 07 '23 at 11:06