You might want to consider Aspect Oriented Programming as a technique for adding cross-cutting behavior, like debug output and logging. (AOP can do a lot more than that, but those are two common uses.)
I am not an expert at AOP, but it might be worth a look.
The Aspect module and associated documents could get you started.