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

Quality of life updates for LoggerFactory #825

Merged
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -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.~>
Expand All @@ -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 {
Expand All @@ -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))
}

}