Skip to content

Conversation

@bpholt
Copy link
Member

@bpholt bpholt commented Apr 24, 2024

From the README:

Given a tagless algebra:

trait MyAlgebra[F[_]] {
  def foo(foo: Int, bar: String): F[Boolean]
}

ensure it has an Aspect[MyAlgebra, Show, Show] instance:

object MyAlgebra {
  implicit val showInt: Show[Int] = Show.fromToString
  implicit val showString: Show[String] = Show.show[String](identity)
  implicit val showBoolean: Show[Boolean] = Show.fromToString
  
  implicit val loggingMyAlgebraAspect: Aspect[MyAlgebra, Show, Show] = Derive.aspect
} 

Then, in a scope where you have an effect F[_] : MonadCancelThrow : Logger, enable
logging by using the withMethodLogging transformation method on an instance of the algebra.

import cats.*
import cats.effect.*
import cats.tagless.*
import cats.tagless.aop.*
import com.dwolla.util.tagless.logging.*
import org.typelevel.log4cats.slf4j.Slf4jFactory

object MyApp extends IOApp.Simple {
  private val fakeMyAlgebra: MyAlgebra[IO] = new MyAlgebra[IO] {
    override def foo(foo: Int, bar: String): IO[Boolean] = IO.pure(true)
  }

  override def run: IO[Unit] =
    Slf4jFactory.create[IO].create.flatMap { implicit logger =>
      fakeMyAlgebra
        .withMethodLogging
        .foo(42, "The Answer to the Ultimate Question of Life, the Universe, and Everything")
        .flatMap(IO.println)
    }
}

Running this results in something like this being printed to the console:

2024-04-24 14:26:41,281 | log_level=INFO  'MyAlgebra.foo(foo=42, bar=The Answer to the Ultimate Question of Life, the Universe, and Everything) returning true'
true

The first line comes from the logging subsystem, which was logback via slf4j.
The second line comes from the IO.println in MyApp.

@bpholt bpholt self-assigned this Apr 24, 2024
@bpholt bpholt requested a review from a team as a code owner April 24, 2024 19:38
fa.codomain.target.guaranteeCase {
case Outcome.Succeeded(out) =>
out.flatMap { a =>
Logger[F].info(s"${fa.algebraName}.${fa.codomain.name}$methodArguments returning ${fa.codomain.instance.show(a)}")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels like this should be pretty easily testable; we should probably add tests before merging this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants