Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add appendLoggerName aspect #893

Merged
merged 5 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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] =
justcoon marked this conversation as resolved.
Show resolved Hide resolved
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
justcoon marked this conversation as resolved.
Show resolved Hide resolved
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
Loading