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 all commits
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.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