Skip to content

Instantly share code, notes, and snippets.

@mpilquist
Created May 11, 2018 15:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpilquist/6ad8e8df141993a31ae577ee8e95e99a to your computer and use it in GitHub Desktop.
Save mpilquist/6ad8e8df141993a31ae577ee8e95e99a to your computer and use it in GitHub Desktop.
import $ivy.`org.typelevel::cats-effect:0.10-22efb61`, cats._, cats.implicits._, cats.effect._, scala.concurrent.duration._
def putStr(msg: String): IO[Unit] = IO(print(msg))
def putStrLn(msg: String): IO[Unit] = IO(println(msg))
def readLn: IO[String] = IO(Console.readLine)
val now: IO[Long] = IO(System.currentTimeMillis)
def time[A](ioa: IO[A]): IO[(FiniteDuration, A)] = for {
start <- now
a <- ioa
end <- now
} yield ((end - start).millis, a)
def currentThread: IO[Thread] = IO(Thread.currentThread)
def currentThreadName: IO[String] = currentThread.map(_.getName)
def log[A: Show](a: A): IO[Unit] = for {
threadName <- currentThreadName
time <- now
msg = show"[$time] ($threadName) $a"
_ <- putStrLn(msg)
} yield ()
def logIO[A: Show](ioa: IO[A]): IO[A] = ioa.flatTap(a => log(a))
def trace[A](desc: String, ioa: IO[A]): IO[A] = for {
_ <- log(s"Before $desc")
result <- time(ioa)
(elapsed, a) = result
_ <- log(s"After $desc - took $elapsed")
} yield a
implicit class IoExtensions[A](val ioa: IO[A]) extends AnyVal {
def log(implicit s: Show[A]): IO[A] = replio.logIO(ioa)
def trace(desc: String): IO[A] = replio.trace(desc, ioa)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment