I am working on an android application codebase where a programmer has properly logged each method. I found it extremely helpful to understand the application flow. This practice saved many debugging efforts to understand the current code flow to identify the buggy method.
So, I am curious about pros and cons of logging each method (Logs are for debug build type only).
So, I am curious, is it a good practice to log every method in aforesaid manner? (we can always put a flag to only enable such logs when needed/while debugging).
On balance, No.
It is certainly not broadly accepted as good practice1.
Here are some pros, and cons:
Yes: if you have implemented it, the trace logging information is useful.
Yes: you can turn the trace logging off.
No: for a non-trivial application, the amount of trace logging could be overwhelming. Too much to store. Too much to analyse. Too much to ask a customer to send you.
No: there is a runtime overhead for logging … even if the logging is disabled with a runtime guard on the logging statement2.
No: the extra logging statements at the start and end of each method are “clutter” that make the code harder to read.
No: assuming the extra logging statements are added by hand, that is extra programming effort, and an extra source of bugs. (And the bugs may be hard to spot in test. Are you going to write unit tests / whatever to check that tracing has been implemented correctly?)
No: trace debugging can change the behavior of your code if it is multi-threaded. For example, turning on tracing can lead to serendipitous synchronization in a non-thread-safe application. This can cause the behavior of a faulty application to change; c.f. a Heisenbug.
Finally, your IDE’s debugger may allow you to log the entry and exit of methods
automatically without doing anything at the source code level. (Of course, this doesn’t help with the Heisenbug issue; see above.)
1 – If it was, you would see this practice in many / most open-source codebases. I can’t recall ever seeing it.
2 – If you find a way disable it with a preprocessor, or build / load time code injection, or
if (compileTimeConstFlag) constructs, you can remove the overheads. But then you lose the flexibility to turn tracing on and off. And the impact on your source code is greater.
Answered By – Stephen C
Answer Checked By – David Marino (BugsFixing Volunteer)