https://kotlinlang.org logo
#ktor
Title
# ktor
h

hdarritchon

05/23/2019, 3:30 PM
Hi everybody, I’d like to log all requests incomming in Ktor with header and body. Currently, I use :
Copy code
install(CallLogging) {
        level = <http://Level.INFO|Level.INFO>
        filter { call -> call.request.path().startsWith("/api/v1") }
        callIdMdc()
    }
And I have some logs like :
200 OK: GET - /api/v1/health
but I’d like to have more details like the header and body because in some case I have log like
Unhandled: POST - /api/v1/catalogEdito/reunion/store
whereas this endpoint exists and returns some datas for certain type of client. So I think I need to have more details to debug and understand what is going on ! Do you know how I can do it please ?
j

Jonathan Mew

05/23/2019, 3:37 PM
perhaps use mdc, similar to how you have used callIdMdc() but picking out the features you are interested in:
Copy code
mdc(LoggingKey("header")) {
  call: ApplicationCall -> call.request.header("someHeaderName")
}
you might need to configure your logging framework to include the mdc information
https://logback.qos.ch/manual/layouts.html#mdc if you use logback for example
h

hdarritchon

05/24/2019, 1:43 PM
Hi @Jonathan Mew I have tested your proposal and it works perfectly well ! Thanks. Please find below my own implementation to log all the headers of a request.
Copy code
install(CallLogging) {
        level = <http://Level.INFO|Level.INFO>
        filter { call -> call.request.path().startsWith("/api/v1") }
        callIdMdc()
        requestHeadersMdc()
    }

fun CallLogging.Configuration.requestHeadersMdc(name: String = "Headers") {
    mdc(name) { call ->
        call.request.headers.entries()
            .map {
                it.key to it.value.joinToString(",")
            }.joinToString(";") {
                "${it.first}:${it.second}"
            }
    }
}
2 Views