Skip to content

Commit

Permalink
Add appendLoggerName aspect
Browse files Browse the repository at this point in the history
  • Loading branch information
somdoron committed Oct 9, 2024
1 parent 6143a2c commit 9058db7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions core/jvm/src/test/scala/zio/logging/AppendLoggerNameSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package zio.logging

import zio.test._
import zio.logging.appendLoggerName
import zio.FiberRef

object AppendLoggerNameSpec extends ZIOSpecDefault {

val spec: Spec[Environment, Any] = suite("AppendLoggerNameSpec")(
test("appendLoggerName") {
for {
name <- FiberRef.currentLogAnnotations.get.map(annotations =>
annotations.get(loggerNameAnnotationKey)
) @@ appendLoggerName("logging") @@ appendLoggerName("zio")

} yield assertTrue(name == Some("zio.logging"))
}
)
}
17 changes: 17 additions & 0 deletions core/shared/src/main/scala/zio/logging/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,23 @@ package object logging extends LoggerLayers {
def loggerName(value: String): ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] =
ZIOAspect.annotated(loggerNameAnnotationKey, value)

/**
* Append logger name aspect, by which it is possible to append a logger name to the current logger name.
* The new name is appended using a dot (.) as the delimiter.
*
* annotation key: [[zio.logging.loggerNameAnnotationKey]]
*/
def appendLoggerName(value: String): ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] =
new ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] {
def apply[R, E, A](zio: ZIO[R, E, A])(implicit trace: Trace): ZIO[R, E, A] =
for {
annotations <- FiberRef.currentLogAnnotations.get
currentLoggerName = annotations.get(loggerNameAnnotationKey)
newLoggerName = currentLoggerName.fold(value)(currentLoggerName => s"$currentLoggerName.$value")
a <- ZIO.logAnnotate(loggerNameAnnotationKey, newLoggerName)(zio)
} yield a
}

implicit final class LogAnnotationZIOSyntax[R, E, A](private val self: ZIO[R, E, A]) {
def logAnnotate[V: Tag](key: LogAnnotation[V], value: V): ZIO[R, E, A] =
self @@ key(value)
Expand Down

0 comments on commit 9058db7

Please sign in to comment.