How can I log the requests a client makes? I've tr...
# http4k
r
How can I log the requests a client makes? I've tried
val reqF = RequestFilters.Tap { Log.d("request", it.toString()) }
, but wrapping that around the client doesn't do it. https://www.http4k.org/guide/howto/structure_your_logs_with_events/ seems to be responses only
d
If you want to debug all content, you can use
DebuggingFilters.PrintRequestAndResponse()
, or just
handler.debug()
. But I'm more interested that you're having problems making the filters work - because we use this type of thing heavily and it very much does! 😉 Can you put a small example together to demonstrate the problem?
r
It's all a bit mushy, I'm trying to translate a ruby mechanize script talking to a browser-oriented API to http4k
d
ah - if you wrap the debugging around the outside of the follow redirects you will only get the original request
it's all about layering!
Copy code
private val browser = FollowRedirects()
        .then(Cookies())
         .then(// insert tap here //)
        .then(http)
r
Ah, getting a csrf token mismatch. Can't really post the sample here though 😞 mechanize (works)
Copy code
ruby
page = agent.get (base + "/login")
login_form = page.form_with(action: base + "/login")
login_form.field_with(id: "login").value = username
login_form.add_field!("password", password)
http4k
Copy code
kotlin
    private val browser = ClientFilters.FollowRedirects()
        .then(ClientFilters.Cookies())
        .then(DebuggingFilters.PrintRequestAndResponse())
        .then(ClientFilters.AcceptGZip())
        .then(client)

        val loginRequest = Request(Method.GET, uri.appendToPath("/login"))
        val loginResponse = browser(loginRequest)
        val loginParsed = loginResponse.parsed()
        val csrf = loginParsed.select("meta[name=csrf-token]").firstOrNull()?.attr("content")
        Log.d("csrf", "$csrf")
        val dashboardRequest = Request(<http://Method.POST|Method.POST>, uri.appendToPath("/login"))
            .form("login", credentials.username)
            .form("password", credentials.password)
            .form("_token", csrf!!)
        val dashboardResponse = browser(dashboardRequest)
        if (dashboardResponse.status != Status.OK) {
            throw Exception("Login didn't work")
        }