Skip to content

Commit e9daa65

Browse files
authored
Add appendLoggerName aspect (#893)
1 parent 01f9e51 commit e9daa65

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package zio.logging
2+
3+
import zio.ZIO
4+
import zio.logging.appendLoggerName
5+
import zio.test._
6+
7+
object AppendLoggerNameSpec extends ZIOSpecDefault {
8+
9+
val spec: Spec[Environment, Any] = suite("AppendLoggerNameSpec")(
10+
test("appendLoggerName") {
11+
for {
12+
name <- ZIO.logAnnotations.map(annotations => annotations.get(loggerNameAnnotationKey)) @@ appendLoggerName(
13+
"logging"
14+
) @@ appendLoggerName("zio")
15+
16+
} yield assertTrue(name == Some("zio.logging"))
17+
}
18+
)
19+
}

core/shared/src/main/scala/zio/logging/package.scala

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,31 @@ package object logging extends LoggerLayers {
5454
def loggerName(value: String): ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] =
5555
ZIOAspect.annotated(loggerNameAnnotationKey, value)
5656

57+
/**
58+
* Logger name aspect, by this aspect is possible to set logger name (in general, logger name is extracted from [[Trace]])
59+
*
60+
* annotation key: [[zio.logging.loggerNameAnnotationKey]]
61+
*/
62+
def loggerName(fn: Option[String] => String): ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] =
63+
new ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] {
64+
def apply[R, E, A](zio: ZIO[R, E, A])(implicit trace: Trace): ZIO[R, E, A] =
65+
for {
66+
annotations <- ZIO.logAnnotations
67+
currentLoggerName = annotations.get(loggerNameAnnotationKey)
68+
newLoggerName = fn(currentLoggerName)
69+
a <- ZIO.logAnnotate(loggerNameAnnotationKey, newLoggerName)(zio)
70+
} yield a
71+
}
72+
73+
/**
74+
* Append logger name aspect, by which it is possible to append a logger name to the current logger name.
75+
* The new name is appended using a dot (.) as the delimiter.
76+
*
77+
* annotation key: [[zio.logging.loggerNameAnnotationKey]]
78+
*/
79+
def appendLoggerName(value: String): ZIOAspect[Nothing, Any, Nothing, Any, Nothing, Any] =
80+
loggerName(currentLoggerName => currentLoggerName.fold(value)(currentLoggerName => s"$currentLoggerName.$value"))
81+
5782
implicit final class LogAnnotationZIOSyntax[R, E, A](private val self: ZIO[R, E, A]) {
5883
def logAnnotate[V: Tag](key: LogAnnotation[V], value: V): ZIO[R, E, A] =
5984
self @@ key(value)

0 commit comments

Comments
 (0)