Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log requests in ktor http client?

I got something like this:

private val client = HttpClient {
    install(JsonFeature) {
        serializer = GsonSerializer()
    }
    install(ExpectSuccess)
}

and make request like

  private fun HttpRequestBuilder.apiUrl(path: String, userId: String? = null) {
    header(HttpHeaders.CacheControl, "no-cache")
    url {
        takeFrom(endPoint)
        encodedPath = path
    }
}

but I need to check request and response body, is there any way to do it? in console/in file?

like image 412
Seko Avatar asked Nov 06 '18 08:11

Seko


1 Answers

Regardless of which client you use or framework you are on, you can implement your own logger like so:

private val client = HttpClient {
    // Other configurations...
    install(Logging) {
        logger = CustomHttpLogger()
        level = LogLevel.BODY
    }
}

Where CustomHttpLogger is any class that implements the ktor Logger interface, like so:

import io.ktor.client.features.logging.Logger

class CustomHttpLogger(): Logger {
    override fun log(message: String) {
        Log.d("loggerTag", message) // Or whatever logging system you want here
    }
}

You can read more about the Logger interface in the documentation here or in the source code here

like image 74
Jacques.S Avatar answered Sep 27 '22 19:09

Jacques.S