Logging best practices

In between all the hyping of the CQ5 healthcheck I want to tell you some bits which has more impact on your daily life as a developer. Today I want to tell you some bits and pieces about logging.

Logging is one of the unloved children of a web project. It’s mostly never stated in the project requirements, but every developer adds logging statements. Everybody has some ideas, what should be logged, but it is never explicitly defined. While I base my recommendations on CQ5 projects, they can be applied widely. And for Java there are — of course — lot of great postings out there, which have tips and tricks on that topic. I just found 10 tips for proper application logging. Sounds pretty good.

But here goes my personal list of best practices (all of them pretty obvious, right?)

  • Use the SLF4J logging framework, as it is the standard logging for sling; there’s no need to introduce another logging framework.
  • Do not use the log levels INFO,WARN and ERROR for debugging your code during development. You won’t have the time to fix them, and then you will pollute the production log with your debugging statements. Your operation people will hate for that, because the CQ5 standard loglevel is “INFO”.
  • Instead use the loglevel “DEBUG” and a special logging configuration for your development environment, which logs your debug statements.
  • Cleanup your debug statements when you are done with development. In production environment I recommend to setup logging on level DEBUG if there are problems with some parts of the application. The last thing I want to see are statements like “loop1”, “Inside for-loop” and “1234” (yes, I have seen them.)
  • Ask yourself: Does a piece of code, which does not have logging statements, really perform any function? Even it is perfect written code with no bugs it is sometimes interesting, what information are processed. So every code should contain debug statements.
  • Stacktraces are sometimes a valuable asset. Which also means, that not always a full stacktrace is required.
  • And the most important: Do not use “System.out.println()”!

If you ask yourself “What should I log”, change perspective. Just imaging that someone strongly assumes an issue in your code. What information do you need to investigate on this? — Add this information in proper DEBUG statements.

So, that’s for today’s lesson. Stay tuned! CQ 5.6 is coming …

Advertisements