From c42cd9f240e92c4dff2fa522b421813f68354255 Mon Sep 17 00:00:00 2001 From: Morgen Peschke Date: Wed, 27 Mar 2024 13:21:59 -0700 Subject: [PATCH] Quality of life updates for LoggerFactory Adds methods to return updated versions that configure the loggers they produce using `addContext` and `withModifiedString`. This should make it easier to migrate from passing around a single `SelfAwareStructuredLogger` and using a `LoggerFactory`. --- .../typelevel/log4cats/LoggerFactory.scala | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/core/shared/src/main/scala/org/typelevel/log4cats/LoggerFactory.scala b/core/shared/src/main/scala/org/typelevel/log4cats/LoggerFactory.scala index 9672373d..55236034 100644 --- a/core/shared/src/main/scala/org/typelevel/log4cats/LoggerFactory.scala +++ b/core/shared/src/main/scala/org/typelevel/log4cats/LoggerFactory.scala @@ -17,6 +17,7 @@ package org.typelevel.log4cats import cats.Functor +import cats.Show.Shown import cats.data.Kleisli import cats.syntax.functor._ import cats.~> @@ -34,6 +35,15 @@ trait LoggerFactory[F[_]] extends LoggerFactoryGen[F] { def mapK[G[_]](fk: F ~> G)(implicit F: Functor[F]): LoggerFactory[G] = LoggerFactory.mapK[F, G](fk)(this) + + def addContext(ctx: Map[String, String])(implicit F: Functor[F]): LoggerFactory[F] = + LoggerFactory.addContext(this, ctx) + + def addContext(pairs: (String, Shown)*)(implicit F: Functor[F]): LoggerFactory[F] = + addContext(pairs.map { case (k, v) => (k, v.toString) }.toMap) + + def withModifiedString(f: String => String)(implicit F: Functor[F]): LoggerFactory[F] = + LoggerFactory.withModifiedString(this, f) } object LoggerFactory extends LoggerFactoryGenCompanion { @@ -60,4 +70,29 @@ object LoggerFactory extends LoggerFactoryGenCompanion { fk(logger) } } + + private def addContext[F[_]: Functor]( + lf: LoggerFactory[F], + ctx: Map[String, String] + ): LoggerFactory[F] = + new LoggerFactory[F] { + override def getLoggerFromName(name: String): SelfAwareStructuredLogger[F] = + lf.getLoggerFromName(name).addContext(ctx) + + override def fromName(name: String): F[SelfAwareStructuredLogger[F]] = + lf.fromName(name).map(_.addContext(ctx)) + } + + private def withModifiedString[F[_]: Functor]( + lf: LoggerFactory[F], + f: String => String + ): LoggerFactory[F] = + new LoggerFactory[F] { + override def getLoggerFromName(name: String): SelfAwareStructuredLogger[F] = + lf.getLoggerFromName(name).withModifiedString(f) + + override def fromName(name: String): F[SelfAwareStructuredLogger[F]] = + lf.fromName(name).map(_.withModifiedString(f)) + } + }