Skip to content

Commit

Permalink
plugin for call loggin til fler loggere
Browse files Browse the repository at this point in the history
  • Loading branch information
rtc11 committed Oct 30, 2024
1 parent 3f2a247 commit 8a59920
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 0 deletions.
7 changes: 7 additions & 0 deletions libs/ktor/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
val ktorVersion = "3.0.0"

dependencies {
api(project(":libs:utils"))

implementation("io.ktor:ktor-server-core:$ktorVersion")
}
20 changes: 20 additions & 0 deletions libs/ktor/main/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Ktor Plugins

## CallLog
Ktor sin `CallLogging` støtter ikke logging til forskjellige loggere.

Hvis man ønsker å logge til både applikasjonslogger og til secure-log kan man bruke denne.

Denne er avhengig av ktor-pluginen `install(DoubleReceive)`.

Usage:
```kotlin
install(DoubleReceive)
install(CallLog) {
exclude { call -> call.request.path().startsWith("/probes") }
log { call ->
appLog.info("${call.request.httpMethod.value} ${call.request.local.uri} gave ${call.response.status()} in ${call.processingTimeMs()}ms")
secureLog.info(call.bodyAsText())
}
}
```
43 changes: 43 additions & 0 deletions libs/ktor/main/libs/ktor/CallLog.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package libs.ktor

import io.ktor.server.application.*
import io.ktor.server.application.hooks.*
import io.ktor.server.request.*
import io.ktor.util.*
import io.ktor.util.date.*
import kotlinx.coroutines.runBlocking

private val CALL_START_TIME = AttributeKey<Long>("CallStartTime")

class CallLogConfig {
var clock: () -> Long = { getTimeMillis() }
var exclusion: (ApplicationCall) -> Boolean = { false }
var action: (ApplicationCall) -> Unit = {}

fun exclude(filter: (ApplicationCall) -> Boolean) {
exclusion = filter
}

fun log(block: (ApplicationCall) -> Unit) {
action = block
}
}

val CallLog = createApplicationPlugin("CallLog", ::CallLogConfig) {
on(CallSetup) { call ->
call.attributes.put(CALL_START_TIME, pluginConfig.clock())
}

on(ResponseSent) { call ->
if (!pluginConfig.exclusion(call)) {
pluginConfig.action(call)
}
}
}

fun ApplicationCall.processingTimeMs(clock: () -> Long = { getTimeMillis() }): Long {
val startTime = attributes[CALL_START_TIME]
return clock() - startTime
}

fun ApplicationCall.bodyAsText(): String = runBlocking { receiveText() }
1 change: 1 addition & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ include(
"libs:kafka",
"libs:mq",
"libs:mq-test",
"libs:ktor",
"libs:task",
"libs:utils",
"libs:ws",
Expand Down

0 comments on commit 8a59920

Please sign in to comment.