6

i am just wondering 'bout use of Logger API in Utility classes while writing java code. we can always use logger where we will be using our utility class to log a proper message BUT what i want to ask is--

Is it a good practice to use Logger in utility classes?

Amit Mutreja
  • 168
  • 1
  • 7

3 Answers3

6

I assume you are writing your own *Util code.

Personally I avoid using Logger in utility classes, because of the "noise" in the log files. If your utility class is well tested, you may remove the log statements.

Just remember to only log, and not perform any business logic in the log statement (whether utility class or not).

E.g. I saw below in one of my projects, and this is not good practice.

log.info("Added = " + list.add("someString"));
RuntimeException
  • 1,593
  • 2
  • 22
  • 31
2
  1. The whole objective of logging in the code is that you should be able debug or look for any abnormal application behavior just by looking into the logs.
  2. So if the utility class you referred hosts an important logic/algorithm which you think logger here will help you debug any issue in future then you should log it.
  3. But if your util class contains concise utility functions where hardly any complex logic is involved then logging should be avoided there.
Santosh
  • 17,667
  • 4
  • 54
  • 79
0

It is a great Idea to use java.util.logging.Logger in all utility classes. The most Java logging frameworks are able to collect Logs from this logger and you won't need to bundle any libraries, because it comes along with the jre.

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
  • 1
    The drawback is that the jul API is pretty slow and ugly. Also, there is a huge performance cost if you redirect these loggers via any framework. If you want to add logging to an application, include slf4j - it's just a single dependency, code is compact, it's fast and it's easy to configure for consumers of your code. – Aaron Digulla Sep 13 '12 at 10:26
  • I think there is a difference for library or applications. If I would package a complete application, I'll add log4j or something else, but if I want other people to include my lib, I wouldn't add a dependency to my code, if not really necessary. – Christian Kuetbach Sep 13 '12 at 12:01
  • IMO, the JUL API has so many drawbacks that it justifies this dependency. – Aaron Digulla Sep 13 '12 at 13:18