Skip to content

Instantly share code, notes, and snippets.

@pierangeloc
Created August 1, 2023 12:27
Show Gist options
  • Save pierangeloc/60fce8a3412e0c4b9800c8e302490cc6 to your computer and use it in GitHub Desktop.
Save pierangeloc/60fce8a3412e0c4b9800c8e302490cc6 to your computer and use it in GitHub Desktop.
Sttp with zio and logging backend
//test it with `runMain com.thenewmotion.myr.TestSttpLogging2 http://httpstat.us/400` from within SBT
object TestSttpLogging2 extends ZIOAppDefault {
override val bootstrap: ZLayer[ZIOAppArgs, Any, Environment] =
Runtime.removeDefaultLoggers >>> SLF4J.slf4j
import sttp.client3.quick._
// curl --request GET \
// --url httpstat.us/200 \
// --header 'user-agent: vscode-restclient'
type ZIOSttpBackend = SttpBackend[Task, ZioStreams with capabilities.WebSockets]
def send(url: String, sttpBackend: ZIOSttpBackend) = {
val delegate = new FollowRedirectsBackend(sttpBackend)
val logger = new Slf4jLogger("pierangelo.logger.HttpLogger", delegate.responseMonad)
val loggingBackend = LoggingBackend(
delegate,
logger,
logRequestBody = true,
logResponseBody = true,
beforeRequestSendLogLevel = LogLevel.Error,
responseLogLevel = statusCode => if (statusCode.isSuccess) LogLevel.Debug else LogLevel.Error,
responseExceptionLogLevel = LogLevel.Error
)
quickRequest.get(uri"$url").header("Accept", "application/json").send(loggingBackend)
}
def request(url: String): ZIO[ZIOSttpBackend, Throwable, Response[String]] = for {
be <- ZIO.service[ZIOSttpBackend]
res <- send(url, be)
} yield res
override def run: ZIO[ZIOAppArgs with Scope, Any, Any] =
for {
_ <- ZIO.logInfo("Before request")
args <- getArgs
res <- request(args(0)).provide(HttpClient.sttpBackend).orDie
_ <- ZIO.logInfo("After request")
} yield res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment