I need to generate debug output in a java appliation that cannot be debugged by placing break points and traces. I've thus far been placing the debug flag as a static variable in one of the classes and then accessing it from all other classes. But this I suspect will eventually cause massive issues later on. What's the best way to do this?

  • What do you do when the flag is set? Do you simply produce some debug output, or are the additional things that you do? – dasblinkenlight Apr 12 '12 at 10:32
  • Produce debug outputs Sys.out.println(); – rsman Apr 12 '12 at 10:46
  • I put a separate DEBUG boolean in each class, so I can turn them on or off as needed. But otherwise, I do what you're suggesting. For me, it's an old habit from my Cobol days. – Gilbert Le Blanc Apr 12 '12 at 16:09

Consider using a logging framework like log4j. Log4j is very flexible and extendible. This is clearly the best option.

If you cannot use such a framework, you have to tell all parts of your program generating debug output, whether this is a debug run or not. This can be done in two ways. Either using static access to some variable/singleton or passing the information to the relevant parts. Both solutions have advantages and disadvantages.

In general the static/singleton pattern is considered harmful because it introduces a global variable and therefore global state which can make testing difficult. However, as long as you are only generating output which does not interfere with any other part of your program you should be fine.

The other approach is to pass the information via a constructor for example. This approach does not hide the dependency of the object on the information and is preferable in theory. However, now you have to pass this information to all classes possibly generating debug output. If you got lots of these classes and/or they are buried deep in the system, you will have to do a lot of boilerplate coding. Dependency injection frameworks (e.g. Guice) are designed to help you with this kind of boilerplate code. If you already use DI this is probably the best way. But if this feels like using a sledge hammer to crack a nut, you should consider using the static access (which is btw what log4j does).

  • +1 especially for pointing out how static affects testability – StuperUser Apr 12 '12 at 10:59

If all you do in response to a flag is producing debug output, then using a logging framework is a better choice: you can set different log levels to individual classes using a centrally located configuration, and control the way the logging information is delivered to you (file, console, database, etc.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.