[kotlin] Ktor Locations 로깅 처리

Ktor는 Kotlin으로 구현된 경량의 웹 프레임워크입니다. Ktor의 Locations 기능을 사용하면 URL 경로와 쿼리 매개변수를 쉽게 다룰 수 있습니다. 그러나 Locations에서 로깅을 처리하는 방법에 대해 명확한 지침이 부족한 경우가 있습니다. 이 포스트에서는 Ktor Locations를 사용하는 동안 로깅을 처리하는 방법에 대해 알아보겠습니다.

1. Ktor Locations란?

Locations는 Ktor에서 경로 및 쿼리 매개변수를 쉽게 다룰 수 있도록 도와주는 기능입니다. Locations를 사용하면 URL 경로를 객체로 매핑하여 추상화할 수 있습니다. 또한 쿼리 매개변수를 처리하는 메커니즘을 제공하여 URL의 파라미터를 쉽게 읽고 쓸 수 있습니다.

2. Ktor Locations의 사용 예제

다음은 Locations를 사용하여 URL 경로와 쿼리 매개변수를 처리하는 예제입니다.

import io.ktor.locations.*
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty

@Location("/user/{id}")
data class UserLocation(val id: Int)

fun Application.module() {
    install(Locations)
    
    routing {
        get<UserLocation> { userLocation ->
            call.respondText("User ID: ${userLocation.id}")
        }
    }
}

fun main() {
    embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}

위 코드는 /user/{id} 경로에 대한 요청을 처리하고 있습니다. 이때 UserLocation 클래스가 URL의 경로를 표현하고 있습니다.

3. Ktor Locations의 로깅 처리

Ktor Locations를 통해 들어오는 요청 및 그에 대한 응답을 로깅하려면 미들웨어를 사용할 수 있습니다. 다음 예제에서는 CallLogging 미들웨어를 사용하여 Locations를 로깅하는 방법을 보여줍니다.

fun Application.module() {
    install(Locations)
    
    install(CallLogging) {
        level = Level.INFO
        filter { call -> call.locations() is UserLocation } 
    }
    
    routing {
        get<UserLocation> { userLocation ->
            call.respondText("User ID: ${userLocation.id}")
        }
    }
}

위의 코드에서 CallLogging 미들웨어를 설치하고, filter 함수를 사용하여 UserLocation을 가진 요청만을 로깅하도록 필터링하고 있습니다. 로깅 수준은 INFO로 설정되어 있습니다.

이제 Locations를 통해 들어온 요청에 대한 로그를 확인할 수 있게 되었습니다.

4. 결론

Ktor의 Locations 기능을 사용하면 URL 경로 및 쿼리 매개변수를 쉽게 다룰 수 있습니다. 또한 원하는 요청에 대한 로깅을 처리하기 위해 CallLogging 미들웨어를 사용할 수 있습니다. 이를 통해 더 나은 디버깅 및 모니터링을 할 수 있게 됩니다.

이상으로 Ktor Locations를 사용하는 동안 로깅을 처리하는 방법에 대한 블로그 포스트를 마치겠습니다.

참고 자료: Ktor 공식 문서