Created
May 11, 2018 15:21
-
-
Save mpilquist/6ad8e8df141993a31ae577ee8e95e99a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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