This post originated from an RSS feed registered with Scala Buzz
by Heiko Seeberger.
Original Post: SLF4S - Logging the Scala way
Feed Title: Heiko Seeberger
Feed URL: http://hseeberger.github.io/atom.xml
Feed Description: About programming and other fun things
Do we need another logging framework in the Java/Scala world? Certainly not! As Scala is fully "downward" compatible to Java, we can use whatever Java logging solution we want. And there are many, aren't there?.
So why SLF4S? Well, SLF4S isn't another logging framework, but a very thin Scala wrapper around SLF4J which has emerged as the leading Java logging solution. Why do we need a Scala wrapper for SLF4S? Well, there are some nice Scala features that can make logging even easier and/or more performant.
First, SLF4J Loggers use by-name parameters which are only evaluated if needed/accessed. When logging "traditionally", we often create messages by concatenating Strings or using the String.format method, even if we don't need these messages in the end because the logging level is not enabled. Of course we could "manually" check whether the logging level is enabled, e.g. by calling logger.isDebugEnabled, but we often don't, because it's cumbersome. With by-name parameters we can simply call our log methods and let SLF4S check whether the log level is enabled. Just take a look at one example:
def debug(msg: => String) { require(msg != null, "msg must not be null!") if (slf4jLogger.isDebugEnabled) slf4jLogger debug msg }
Second, SLF4S offers a Logging trait which can be mixed into any class to make a Logger instance available. That particular Logger will be initialized with the name of the class it is mixed into which is a common use case.
class MyClazz extends SomeClazz with Logging ... logger debug "SLF4S just rocks!" ...
Of course you can create Loggers with arbitrary names by calling Logger("SomeSpecialName").
Last but not least, SLF4S offers implicit conversions from "usual" SLF4J Loggers into "pimped" SLF4S Loggers.
Ah, and of course, SLF4S is OSGi compliant. But that's not a big surprise, taking into account that the authors are OSGi fanboys and SLF4J is OSGi compliant, too.