diff --git a/core/jvm/src/test/scala/zio/logging/AppendLoggerNameSpec.scala b/core/jvm/src/test/scala/zio/logging/AppendLoggerNameSpec.scala new file mode 100644 index 00000000..a2d0ca21 --- /dev/null +++ b/core/jvm/src/test/scala/zio/logging/AppendLoggerNameSpec.scala @@ -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")) + } + ) +} diff --git a/core/shared/src/main/scala/zio/logging/package.scala b/core/shared/src/main/scala/zio/logging/package.scala index 4e3e0c4a..4898f5b5 100644 --- a/core/shared/src/main/scala/zio/logging/package.scala +++ b/core/shared/src/main/scala/zio/logging/package.scala @@ -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)