ProductPromotion
Logo

Scala

made by https://0x3d.site

GitHub - lightbend-labs/scala-logging: Convenient and performant logging library for Scala wrapping SLF4J.
Convenient and performant logging library for Scala wrapping SLF4J. - lightbend-labs/scala-logging
Visit Site

GitHub - lightbend-labs/scala-logging: Convenient and performant logging library for Scala wrapping SLF4J.

GitHub - lightbend-labs/scala-logging: Convenient and performant logging library for Scala wrapping SLF4J.

Scala Logging is a convenient and fast logging library wrapping SLF4J.

It's convenient, because you can simply call log methods, without checking whether the respective log level is enabled:

logger.debug(s"Some $expensive message!")

It's fast, because thanks to Scala macros the check-enabled-idiom is applied and the following code is generated:

if (logger.isDebugEnabled) logger.debug(s"Some $expensive message!")

Prerequisites

  • Java 8 or higher
  • Scala 2.11, 2.12, 2.13 or 3.0
  • Logging backend compatible with SLF4J

A compatible logging backend is Logback, add it to your sbt build definition:

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.10"

If you are looking for a version compatible with Scala 2.10, check out Scala Logging 2.x.

Getting Scala Logging

Scala Logging is published to Sonatype OSS and Maven Central:

  • Group id / organization: com.typesafe.scala-logging
  • Artifact id / name: scala-logging

sbt users may add this to their build.sbt:

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.9.4"

Using Scala Logging

The Logger class from the com.typesafe.scalalogging package wraps an underlying SLF4J logger. In order to create a Logger, you pass a name to the apply factory method defined in the Logger companion object:

val logger = Logger("name")

Or, you pass in a SLF4J logger instance:

val logger = Logger(LoggerFactory.getLogger("name"))

Or, you pass in the name of the class into which it is defined:

val logger = Logger(getClass.getName)

Or, you pass in a class:

val logger = Logger(classOf[MyClass])

Or, using the runtime class wrapped by the implicit class tag parameter:

val logger = Logger[MyClass]

The LazyLogging and StrictLogging traits from the com.typesafe.scalalogging package define the logger member as a lazy or strict value respectively, whereas the AnyLogging trait defines an abstract logger.

It depends on the individual use case which trait to use. However, we have defined some scenarios where you can use these traits:

  • Use LazyLogging if you are creating lots of objects with this trait repetitively.
  • Use StrictLogging pretty much by default, especially if the class is a singleton, or you know the log methods will always be invoked.
  • Use AnyLogging when writing some trait which needs access to any logger without deciding on a specific implementation.

In case of LazyLogging and StrictLogging, the underlying SLF4J logger is named according to the class into which these traits are mixed:

class LazyLoggingExample extends LazyLogging {
  logger.debug("This is Lazy Logging ;-)")

  logger.whenDebugEnabled {
    println("This would only execute when the debug level is enabled.")
    (1 to 10).foreach(x => println("Scala logging is great!"))
  }
}
class StrictLoggingExample extends StrictLogging {
  logger.debug("This is Strict Logging ;-)")

  logger.whenDebugEnabled {
    println("This would only execute when the debug level is enabled.")
    (1 to 10).foreach(x => println("Scala logging is great!"))
  }
}
class AnyLoggingExample extends AnyLogging {
  override protected val logger: Logger = Logger("name")

  logger.info("This is Any Logging ;-)")

  logger.whenInfoEnabled {
    println("This would only execute when the info level is enabled.")
    (1 to 10).foreach(x => println("Scala logging is great!"))
  }
}

LoggerTakingImplicit provides the same methods as Logger class, but with additional implicit parameter A. During creation of the LoggerTakingImplicit evidence CanLog[A] is required. It may be useful when contextual parameter (e.g. Correlation ID) is being passed around and you would like to include it in the log messages:

case class CorrelationId(value: String)
implicit case object CanLogCorrelationId extends CanLog[CorrelationId] {
  override def logMessage(originalMsg: String, a: CorrelationId): String = s"${a.value} $originalMsg"
}

implicit val correlationId = CorrelationId("ID")

val logger = Logger.takingImplicit[CorrelationId]("test")
logger.info("Test") // takes implicit correlationId and logs "ID Test"

If you want to extract the context object associated with your logger i.e. correlationId here, use getContext.

val context = logger.canLogEv.getContext()

It's also possible to use MDC through CanLog without any troubles with execution context.

case class CorrelationId(value: String)
implicit case object CanLogCorrelationId extends CanLog[CorrelationId] {
  override def logMessage(originalMsg: String, a: CorrelationId): String = {
    MDC.put("correlationId", a.value)
    originalMsg
  }

  override def afterLog(a: CorrelationId): Unit = {
    MDC.remove("correlationId")
  }
}

implicit val correlationId = CorrelationId("ID")

val logger = Logger.takingImplicit[CorrelationId]("test")

def serviceMethod(implicit correlationId: CorrelationId): Future[Result] = {
  dbCall.map { value =>
    logger.trace(s"Received value $value from db") // takes implicit correlationId
    toResult(value)
  }
}

String Interpolation

It is idiomatic to use Scala's string interpolation logger.error(s"log $value") instead of SLF4J string interpolation logger.error("log {}", value). However there are some tools (such as Sentry) that use the log message format as grouping key. Therefore they do not work well with Scala's string interpolation.

Scala Logging replaces simple string interpolations with their SLF4J counterparts like this:

logger.error(s"my log message: $arg1 $arg2 $arg3")
logger.error("my log message: {} {} {}", arg1, arg2, arg3)

This has no effect on behavior and performace should be comparable (depends on the underlying logging library).

Limitations

  • Works only when string interpolation is directly used inside the logging statement. That is when the log message is static (available at compile time).
  • Works only for the logger.<level>(message) and logger.<level>(marker, message) logging methods. It does not work if you want to log an exception and use string interpolation too (this is a limitation of the SLF4J API).

Line numbers in log message?

Using the sourcecode library, it's possible to add line number information (especially useful for debugging):

def foo(arg: String)(implicit line: sourcecode.Line, file: sourcecode.File) = {
  ... do something with arg ...
  ... do something with file.value ...
}

foo("hello") // the implicit sourcecode.File is filled in automatically

Maintenance status

This library is community-maintained. It is not supported under the Lightbend subscription.

Contribution policy

Contributions via GitHub pull requests are gladly accepted from their original author. Before we can accept pull requests, you will need to agree to the Lightbend Contributor License Agreement online, using your GitHub account.

More Resources
to explore the angular.

mail [email protected] to add your project or resources here 🔥.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory