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?
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
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).
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.)