The scala-logging is a convenient logging library warpping slf4j logging API.

1 Getting Started

To use scala-logging, import it and one of Sl4j implementations such as logback.

1
2
ivy"com.typesafe.scala-logging::scala-logging:3.9.2",
ivy"ch.qos.logback:logback-classic:1.2.3"

2 Creating a Logger

There are two ways to create a logger instance: one using the factory as the following

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import com.typesafe.scalalogging.Logger

// for stirng name
val logger1 = Logger("name")
val logger2 = Logger(LoggerFactory.getLogger("name"))

// for class name
val logger3 = Logger(classOf[MyClass])
val logger4 = Logger[MyClass]

// for object name
val logger5 = Logger(myObj.getClass)

logger1.info("my message.")

3 Mixing Trait

The other way is to mix one of the two traits: LazyLogging or StrictLogging. The difference is that the LazyLogging create a lzay logger instance: protected lazy val logger: Logger = Logger(LoggerFactory.getLogger(getClass.getName)).

1
2
3
4
class MyClass extends LazyLogging {
  logger.debug("This is very convenient ;-)")
  ...
}

The log methods such as error, warn etc are implemented using Scala macro. The macro implement actually performs one task: it checks the log level before message logging.