Skip to content

Instantly share code, notes, and snippets.

@markosski
Last active February 6, 2021 17:37
Show Gist options
  • Save markosski/715d2f116b7658c07fd859ee73ee2134 to your computer and use it in GitHub Desktop.
Save markosski/715d2f116b7658c07fd859ee73ee2134 to your computer and use it in GitHub Desktop.
import zio._
object logging {
type Logging = Has[Logging.Service]
object Logging {
trait Service {
def info(msg: String, data: Map[String, Any] = Map()): Task[Unit]
}
def liveWithData(initData: Map[String, Any]): Layer[Nothing, Logging] = ZLayer.succeed {
new Service {
def info(msg: String, data: Map[String, Any]) = Task(println(initData ++ data + ("message" -> msg)))
}
}
val live = liveWithData(Map())
def info(msg: String, data: Map[String, Any] = Map()): RIO[Logging, Unit] =
ZIO.accessM(_.get.info(msg, data))
}
}
import logging._
object DomainOps {
def doAnotherThing[E <: Logging]: RIO[E, Unit] = for {
_ <- Logging.info("did something")
} yield ()
}
def doSomething[E <: Logging]: RIO[E, Unit] = for {
_ <- Logging.info("...")
_ <- DomainOps.doAnotherThing // <- How to update Logging with new context data
} yield ()
val rts = zio.Runtime.default
rts.unsafeRun(doSomething.provideLayer(Logging.liveWithData(Map("foo" -> "bar"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment