How to force Logger.debug output in Play! framework specs2 tests?

Rajish picture Rajish · Jul 22, 2012 · Viewed 9.5k times · Source

By default all Logger output, visible when an application is running, is mute when the application is tested.

How to force the debugs, infos etc. to be shown in the specs2 reports?

Answer

rintcius picture rintcius · Jul 24, 2012

First off, you may like some background why logging is disabled in test mode. This was Guillame Bort's answer to a question in the play forum (see this thread):

The logger is disabled in test mode for now because it was causing an huge PermGen space leak when running tests. But we are working to run tests in a forked JVM so we will enable it again soon.

As a workaround, I created my own logger like this (Scala code):

import play.api.{Play, LoggerLike, Logger}
import org.slf4j.LoggerFactory
import org.slf4j.impl.SimpleLoggerFactory

object MyLogger extends LoggerLike {

  val factory = if (Play.isTest(Play.current)) {
    new SimpleLoggerFactory()
  } else {
    LoggerFactory.getILoggerFactory
  }

  val redirectDebugToInfo = factory.isInstanceOf[SimpleLoggerFactory]

  val logger = factory.getLogger("application")

  def apply(name: String): Logger = new Logger(factory.getLogger(name))

  def apply[T](clazz: Class[T]): Logger = new Logger(factory.getLogger(clazz.getCanonicalName))

  // this method is to make debug statements to show up in test mode
  override def debug(m: => String) = {
    if (redirectDebugToInfo) {
      info(m)
    } else {
      super.debug(m)
    }
  }
}

I don't know how this code behaves regarding the PermGen leak in general, but so far I didn't have that problem. To make it work you need to add this dependency:

"org.slf4j" % "slf4j-simple" % "1.6.4"