Created
August 1, 2023 12:27
-
-
Save pierangeloc/60fce8a3412e0c4b9800c8e302490cc6 to your computer and use it in GitHub Desktop.
Sttp with zio and logging backend
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
//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