Skip to content

Commit

Permalink
Merge pull request #1525 from sgeorgakis/master
Browse files Browse the repository at this point in the history
[SCALA-622] Logging in ZIO app
  • Loading branch information
dominiqueplante authored Sep 23, 2024
2 parents a7b5c7a + 032c040 commit a28cef6
Show file tree
Hide file tree
Showing 6 changed files with 162 additions and 0 deletions.
7 changes: 7 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,13 @@ lazy val zio2 = (project in file("zio-2"))
libraryDependencies += "dev.zio" %% "zio-json" % "0.7.3",
libraryDependencies += "dev.zio" %% "zio-test" % zioVersion % Test,
libraryDependencies += "dev.zio" %% "zio-test-sbt" % zioVersion % Test,
libraryDependencies += "dev.zio" %% "zio-logging" % "2.1.10",
libraryDependencies += "dev.zio" %% "zio-logging-slf4j2" % "2.1.10",
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.5.6",
// used in the article, but can't work with zio-logging-slf4j2 dependency
// libraryDependencies += "dev.zio" %% "zio-logging-slf4j2-bridge" % "2.1.10",
libraryDependencies += "dev.zio" %% "zio-metrics-connectors" % "2.1.0",
libraryDependencies += "dev.zio" %% "zio-metrics-connectors-prometheus" % "2.1.0",
libraryDependencies ++= scalaTestDeps,
testFrameworks += new TestFramework("zio.test.sbt.ZTestFramework")
)
Expand Down
12 changes: 12 additions & 0 deletions zio-2/src/main/resources/logback.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.baeldung.scala.zio.logging

import zio.*
import zio.logging.backend.SLF4J
import zio.logging.{
LogColor,
LogFilter,
LogFormat,
LoggerNameExtractor,
console,
fileJson
}
import zio.logging.LogFormat.*

import java.nio.file.Path
import java.time.format.DateTimeFormatter

object BaeldungLogger {

private val filter =
LogFilter.logLevelByName(
LogLevel.Trace,
("com.baeldung.scala.zio.logging", LogLevel.Info)
)

private val logFormat: LogFormat = timestamp(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssAZ")
).highlight(_ => LogColor.BLUE)
|-| bracketStart |-| LogFormat.loggerName(
LoggerNameExtractor.trace
) |-| text(":") |-| traceLine |-| bracketEnd |-|
fiberId |-| level.highlight |-| label("message", quoted(line)).highlight

val consoleLogger: ULayer[Unit] =
Runtime.removeDefaultLoggers >>> console(logFormat, filter)

val fileLogger: ULayer[Unit] = Runtime.removeDefaultLoggers >>> fileJson(
Path.of("baeldung-zio-logging.log"),
logFormat,
LogLevel.Debug
)

val slf4jLogger: ULayer[Unit] = Runtime.removeDefaultLoggers >>> SLF4J.slf4j

// val slf4jBridgeLogger: ULayer[Unit] = Runtime.removeDefaultLoggers >>> Slf4jBridge.initialize

val combinedLogger: ULayer[Unit] = consoleLogger ++ fileLogger

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.baeldung.scala.zio.logging

import zio.*
import zio.logging.*
import zio.metrics.connectors.MetricsConfig
import zio.metrics.connectors.prometheus.{
PrometheusPublisher,
prometheusLayer,
publisherLayer
}

import java.io.IOException

object BaeldungMetricsLogger {

private val prometheusConnector
: ZLayer[Unit, IOException, PrometheusPublisher] = (ZLayer.succeed(
MetricsConfig(10.millis)
) ++ publisherLayer) >+> prometheusLayer
val metricsLogger: ZLayer[Unit, IOException, PrometheusPublisher] =
logMetrics ++ logMetricsWith(
"custom_log_counter",
"log_level"
) ++ prometheusConnector

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.baeldung.scala.zio.logging

import zio.*
import zio.metrics.connectors.prometheus.PrometheusPublisher

object BaeldungZIOLoggingApp extends ZIOAppDefault {

val app: ZIO[PrometheusPublisher, Any, Unit] = for {
- <- ZIO.logTrace("This is a trace message")
_ <- ZIO.logDebug("This is a debug message")
_ <- ZIO.logInfo("This is an info message")
_ <- ZIO.logWarning("This is a warning message")
_ <- ZIO.logError("This is an error message")
_ <- ZIO.sleep(500.millis)
metricValues <- ZIO.serviceWithZIO[PrometheusPublisher](_.get)
_ <- Console.printLine(metricValues)
} yield ()

override def run: ZIO[ZIOAppArgs & Scope, Any, Any] =
app.provideLayer(
BaeldungLogger.slf4jLogger >>> BaeldungMetricsLogger.metricsLogger
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.baeldung.scala.zio.logging

import zio.{Chunk, LogLevel, ZIO}
import zio.test.Assertion.*
import zio.test.*
import zio.*

object BaeldungZIOLoggingUnitTest extends ZIOSpecDefault {

override def spec: Spec[TestEnvironment, Any] =
suite("BaeldungZIOLoggingSpec")(
test("log trace level") {
for {
- <- ZIO.logTrace("This is a trace message")
_ <- ZIO.logDebug("This is a debug message")
_ <- ZIO.logInfo("This is an info message")
_ <- ZIO.logWarning("This is a warning message")
_ <- ZIO.logError("This is an error message")
loggerOutput <- ZTestLogger.logOutput
} yield assertTrue(loggerOutput.size == 5) &&
assert(loggerOutput.map(_.logLevel))(
equalTo(
Chunk(
LogLevel.Trace,
LogLevel.Debug,
LogLevel.Info,
LogLevel.Warning,
LogLevel.Error
)
)
) &&
assert(loggerOutput.map(_.message()))(
equalTo(
Chunk(
"This is a trace message",
"This is a debug message",
"This is an info message",
"This is a warning message",
"This is an error message"
)
)
)
}
).provideLayer(Runtime.removeDefaultLoggers >>> ZTestLogger.default)
}

0 comments on commit a28cef6

Please sign in to comment.