呼叫記錄 (Call logging)
必要相依性:io.ktor:ktor-server-call-logging
程式碼範例: logging
原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。 支援:✖️
Ktor 提供了使用 SLF4J 程式庫記錄應用程式事件的功能。你可以從 Ktor 伺服器中的記錄 主題了解一般記錄設定。
CallLogging 外掛程式可讓你記錄連入的用戶端請求。
新增相依性
若要使用 CallLogging,請將 ktor-server-call-logging 構件新增至你的建置指令碼:
implementation(ktorLibs.server.callLogging)implementation ktorLibs.server.callLogging<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-call-logging-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>安裝 CallLogging
若要將 CallLogging 外掛程式安裝至你的應用程式,請將其傳遞給指定 模組模組可讓您透過對路由進行分組來建構應用程式。 中的 install 函式。 以下範例展示如何安裝 CallLogging:
- 在
embeddedServer()函式呼叫中。 - 在
Application類別上明確定義的module()擴充函式中。
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.calllogging.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(CallLogging)
// ...
}.start(wait = true)
}import io.ktor.server.application.*
import io.ktor.server.plugins.calllogging.*
// ...
fun Application.module() {
install(CallLogging)
// ...
}配置記錄設定
你可以透過多種方式配置 CallLogging:指定記錄層級、根據指定條件篩選請求、自訂記錄訊息等。你可以在 CallLoggingConfig 查看可用的組態設定。
設定記錄層級
預設情況下,Ktor 使用 Level.INFO 記錄層級。若要變更它,請使用 level 屬性:
install(CallLogging) {
level = Level.INFO
}篩選記錄請求
filter 屬性允許你新增用於篩選請求的條件。在以下範例中,只有傳送至 /api/v1 的請求才會被記錄:
install(CallLogging) {
filter { call ->
call.request.path().startsWith("/api/v1")
}
}自訂記錄訊息格式
透過使用 format 函式,你可以將與請求/回應相關的任何資料放入記錄中。以下範例展示了如何為每個請求記錄回應狀態、請求 HTTP 方法以及 User-Agent 標頭值。
install(CallLogging) {
format { call ->
val status = call.response.status()
val httpMethod = call.request.httpMethod.value
val userAgent = call.request.headers["User-Agent"]
"Status: $status, HTTP method: $httpMethod, User agent: $userAgent"
}
}你可以在此處找到完整範例:logging。
將呼叫參數放入 MDC
CallLogging 外掛程式支援 MDC(Mapped Diagnostic Context)。你可以使用 mdc 函式將具有指定名稱的所需上下文值放入 MDC。例如,在下方的程式碼片段中,將 name 查詢參數新增至 MDC:
install(CallLogging) {
mdc("name-parameter") { call ->
call.request.queryParameters["name"]
}
}你可以在 ApplicationCall 生命週期內存取新增的值:
import org.slf4j.MDC
// ...
MDC.get("name-parameter")