Skip to content

Commit

Permalink
Add appendLoggerName aspect (#893)
Browse files Browse the repository at this point in the history
  • Loading branch information
somdoron authored Oct 11, 2024
1 parent 01f9e51 commit e9daa65
Show file tree
Hide file tree
Showing 2 changed files with 44 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.ZIO
import zio.logging.appendLoggerName
import zio.test._

object AppendLoggerNameSpec extends ZIOSpecDefault {

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

} yield assertTrue(name == Some("zio.logging"))
}
)
}
25 changes: 25 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,31 @@ package object logging extends LoggerLayers {
def loggerName(value: String): ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] =
ZIOAspect.annotated(loggerNameAnnotationKey, value)

/**
* Logger name aspect, by this aspect is possible to set logger name (in general, logger name is extracted from [[Trace]])
*
* annotation key: [[zio.logging.loggerNameAnnotationKey]]
*/
def loggerName(fn: Option[String] => 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 <- ZIO.logAnnotations
currentLoggerName = annotations.get(loggerNameAnnotationKey)
newLoggerName = fn(currentLoggerName)
a <- ZIO.logAnnotate(loggerNameAnnotationKey, newLoggerName)(zio)
} yield a
}

/**
* 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] =
loggerName(currentLoggerName => currentLoggerName.fold(value)(currentLoggerName => s"$currentLoggerName.$value"))

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 e9daa65

Please sign in to comment.