|
| 1 | +package com.baeldung.scala.logging |
| 2 | + |
| 3 | +import com.typesafe.scalalogging.{CanLog, LazyLogging, Logger, StrictLogging} |
| 4 | +import org.slf4j.LoggerFactory |
| 5 | + |
| 6 | +class ScalaLoggingSample { |
| 7 | + |
| 8 | + val loggerV1 = Logger("BaeldungLogger") |
| 9 | + val loggerV2 = Logger(getClass.getName) |
| 10 | + val loggerV3 = Logger(classOf[ScalaLoggingSample]) |
| 11 | + val loggerV4 = Logger[ScalaLoggingSample] |
| 12 | + val loggerV5 = Logger(LoggerFactory.getLogger("FromSlf4jLogger")) |
| 13 | + |
| 14 | +} |
| 15 | +case class RequestId(id: String) |
| 16 | + |
| 17 | +object LoggingImplicits { |
| 18 | + implicit case object WithRequestId extends CanLog[RequestId] { |
| 19 | + override def logMessage(originalMsg: String, a: RequestId): String = |
| 20 | + s"[REQ: ${a.id}] $originalMsg" |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +object TestApp extends App { |
| 25 | + val sample = new ScalaLoggingSample |
| 26 | + sample.loggerV1.info("This is an info message") |
| 27 | + sample.loggerV2.error("This is an error message") |
| 28 | + sample.loggerV3.warn("This is a warning message") |
| 29 | + sample.loggerV4.debug("This is a debug message") |
| 30 | + sample.loggerV5.trace("This is a trace message") |
| 31 | + |
| 32 | + sample.loggerV5.whenDebugEnabled { |
| 33 | + println("This block is executed only if logger level is DEBUG") |
| 34 | + } |
| 35 | + |
| 36 | + def contextUsageMethod = { |
| 37 | + import LoggingImplicits._ |
| 38 | + val ctxLogger = Logger.takingImplicit[RequestId]("ContextLogger") |
| 39 | + implicit val reqId = RequestId("user-1234") |
| 40 | + println() |
| 41 | + println() |
| 42 | + println() |
| 43 | + val message = "This is a message with user request context" |
| 44 | + ctxLogger.info(message) |
| 45 | + } |
| 46 | + |
| 47 | + contextUsageMethod |
| 48 | + |
| 49 | + val country = "India" |
| 50 | + val capital = "NewDelhi" |
| 51 | + sample.loggerV5.info(s"$capital is the capital of $country") |
| 52 | + val slf4jLogger = sample.loggerV5.underlying |
| 53 | + slf4jLogger.info("{} is the capital of {}", capital, country) |
| 54 | +} |
| 55 | + |
| 56 | +class LazyLoggingSample extends LazyLogging { |
| 57 | + logger.info("This is from lazy logging") |
| 58 | +} |
| 59 | +class StrictLoggingSample extends StrictLogging { |
| 60 | + logger.info("This is from strict logging") |
| 61 | +} |
0 commit comments