TDD – Do We Need Logging When Doing TDD?

designloggingobject-orientedtddunit testing

When doing the Red, Green & Refactor cycle we should always write the minimum code to pass the test. This is the way I have been taught about TDD and the way almost all books describe the process.

But what about the logging?

Honestly I have rarely used logging in an application unless there was something really complicated that was happening, however, I have seen numerous posts that talk about the importance of proper logging.
So other than logging an exception I couldn't justify the real importance of logging in a proper tested application (unit/integration/acceptance tests).

So my questions are:

  1. Do we need to log if we are doing TDD? won't a failing test reveal
    what wrong with the application?
  2. Should we add test for the logging process in each method in each class?
  3. If some log levels are disabled in the production environment for example, won't that introduce a dependency between the tests and enviroment?
  4. People talk about how logs ease debugging, but one of the main advantages about TDD is that I always know what's wrong due to a failing test.

Is there something I am missing out there?

Best Answer

1) Do we need to log if we are doing TDD? won't a failing test reveal what wrong with the application?

That assumes you have every possible test your application needs, which is rarely true. Logs help you track down bugs you did not write tests for yet.

2) Should we add test for the logging process in each method in each class?

If the logger itself is tested, it would not need to be retested in each class, similar to other dependencies.

3) If some log levels are disabled in the production environment for example, won't that introduce a dependency between the tests and environment?

Humans (and log aggregators) depend on the logs, the tests should not depend on them. Typically there are several log levels, and some are used in production, and some additional levels are used in development, similar to:

"Rails log level is info in production mode and debug in development and test" - http://guides.rubyonrails.org/debugging_rails_applications.html

Other applications use a similar approach.

4) People talk about how logs ease debugging, but one of the main advantages about TDD is that I always know what's wrong due to a failing test.

Production bugs will have passed all the tests, so you may need some other reference to investigate those issues.

Related Topic