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

A working example in README.md #151

Open
sshark opened this issue Mar 29, 2019 · 0 comments
Open

A working example in README.md #151

sshark opened this issue Mar 29, 2019 · 0 comments

Comments

@sshark
Copy link

sshark commented Mar 29, 2019

The example I copied from README.md cannot be compiled correctly without modifications. I also suggest making it executable. I find it helpful to someone like me who is unfamiliar with this style of logging.

While we are at it, is the unsafeLogger defined at (A) considered impure? Thanks

import io.chrisdavenport.log4cats.Logger
import io.chrisdavenport.log4cats.slf4j.Slf4jLogger
import cats.effect.{ExitCode, IO, IOApp, Sync}
import cats.implicits._

object MyThing extends IOApp {

  // Arbitrary Local Function Declaration
  def doSomething[F[_]: Sync]: F[Unit] = {
    // Impure But What 90% of Folks I know do with log4s
    implicit def unsafeLogger[F[_]: Sync] = Slf4jLogger.getLogger[F]

    Logger[F].info("Logging Start Something") *>
      Sync[F].delay(println("I could be doing anything")).attempt.flatMap {
        case Left(e)  => Logger[F].error(e)("Something Went Wrong")
        case Right(_) => Sync[F].pure(())
      }
  }

  def safelyDoThings[F[_]: Sync]: F[Unit] =
    for {
      logger <- Slf4jLogger.create[F]
      _      <- logger.info("Logging at start of safelyDoThings")
      something <- Sync[F]
        .delay(println("I could do anything"))
        .onError { case e => logger.error(e)("Something Went Wrong in safelyDoThings") }
      _ <- logger.info("Logging at end of safelyDoThings")
    } yield something

  def passForEasierUse[F[_]: Sync: Logger] =
    for {
      _ <- Logger[F].info("Logging at start of passForEasierUse")
      something <- Sync[F]
        .delay(println("I could do anything"))
        .onError { case e => Logger[F].error(e)("Something Went Wrong in passForEasierUse") }
      _ <- Logger[F].info("Logging at end of passForEasierUse")
    } yield something

  override def run(args: List[String]): IO[ExitCode] =
    doSomething[IO] *>
      MyThing.safelyDoThings[IO] *> {

      // Impure But What 90% of Folks I know do with log4s
      implicit def unsafeLogger[F[_]: Sync] = Slf4jLogger.getLogger[F]    // (A)

      MyThing.passForEasierUse[IO]
    } *>
      IO(ExitCode.Success)
}

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

No branches or pull requests

1 participant