Why am I receiving a null value for call.response....
# ktor
t
Why am I receiving a null value for call.response.status() when using a custom plugin?
Copy code
val FileLogger = createApplicationPlugin(name = "FileLogger", createConfiguration = ::PluginConfiguration) {
    val path = pluginConfig.path
    val logFile = File(path)
    val gson = Gson()

    onCall { call ->
        val uri = call.request.uri
        val status = call.response.status()
        val httpMethod = call.request.httpMethod.value
        val userAgent = call.request.headers["User-Agent"]
        val timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)

        val logEntry = gson.toJson(object: LogMessage {
            override var timestamp = "$timestamp"
            override var status = "$status"
            override var method = "$httpMethod"
            override var path = "$uri"
            override var userAgent = "$userAgent"
        })

        logFile.appendText("$logEntry\n")
    }
}
everything else is populated but status is always null (side note, is it possible to report error messages here?)
r
because
onCall { ... }
is called before routing, so you probably haven’t called
call.respond(...)
yet. try to change it to
onCallRespond { ... }
t
alright, ill try that
Intresting, for routes that have
HttpStatusCode.OK
in their
call.respond
it is not null now, but routes without a set status are null
and normal 404's still report as null
r
yes, you are right, it happens before body is transformed.
on(ResponseSent) { ... }
is what you need. But why don’t you just config
CallLogging
to write to file in json format?
also, please note, that file write operations are blocking and do not work well with coroutines
t
I was not actually sure how to disable logging to console with CallLogging