Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save seahrh/e7b64c24a941ff9dd51446b28c098d21 to your computer and use it in GitHub Desktop.
Save seahrh/e7b64c24a941ff9dd51446b28c098d21 to your computer and use it in GitHub Desktop.
Logback: Disable all logging in unit tests

After scouring the internet and piece-mealing together the correct way to do this, here is a step-by-step, all-in-one-place guide to making logback STFU when running your unit tests.

Here's how to do it

Save the following as logback-test.xml under src/test/resources:

<configuration>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>
  <root level="OFF">
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

Bonus: Disabling logging when testking akka actors

If you're using akka-testkit, make sure you pass a config string that tells akka to turn off logging.

package whatever

import akka.actor.ActorSystem
import akka.testkit.{ TestKit, ImplicitSender }
import com.typesafe.config.ConfigFactory
import org.scalatest.WordSpecLike
import org.scalatest.Matchers
import org.scalatest.BeforeAndAfterAll

class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
  with WordSpecLike with Matchers with BeforeAndAfterAll {
 
  def this() = this(ActorSystem("MySpec", ConfigFactory.parseString("""
    akka.loggers = ["akka.testkit.TestEventListener"]
    akka.stdout-loglevel = "OFF"
    akka.loglevel = "OFF"
  """)))
  
  // stuff
}

At Refinery29 we've abstracted this into a base ActorSpec class we can extend our actor tests from

package whatever

import java.util.UUID

import akka.actor.ActorSystem
import akka.testkit.{ ImplicitSender, TestKit }
import com.typesafe.config.ConfigFactory

import org.scalatest.{ BeforeAndAfterAll, Matchers, OneInstancePerTest, WordSpecLike }

/**
 * Used as the base class when testing actors.
 * Provides automatic setup and teardown of ActorSystems, and bootstraps the ActorSystem
 * to suppress annoying logging.
 */
abstract class ActorSpec(_system: ActorSystem) extends TestKit(_system)
    with ImplicitSender with WordSpecLike with OneInstancePerTest with Matchers with BeforeAndAfterAll {

  def this() = this(ActorSystem(s"ActorSpec-${UUID.randomUUID}", ConfigFactory.parseString("""
    akka.loggers = ["akka.testkit.TestEventListener"]
    akka.stdout-loglevel = "OFF"
    akka.loglevel = "OFF"
  """)))

  override def afterAll {
    TestKit.shutdownActorSystem(system)
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment