1

试图监控我们的 Ktor 后端应用程序的性能,并能够将 Elastic APM 代理附加到它。服务器在 Kibana 仪表板中作为服务可见。但它不会为每个传入请求自动创建事务。当我们手动启动事务并在特定路由中结束它时,它只会记录该请求的性能。有没有其他方法可以解决这种情况?

尝试了以下方法

  1. 在设置阶段拦截每个请求并启动事务,但在最后拦截相同的调用时无法结束事务面临的问题。
  2. 对于在下面一段代码中定义的控制器/路由中的每个请求,它都在工作。
    get("/api/path") {
        val transaction: Transaction = ElasticApm.startTransaction()
        try {
            transaction.setName("MyTransaction#getApi")
            transaction.setType(Transaction.TYPE_REQUEST)
            // do business logic and response
         } catch (e: java.lang.Exception) {
            transaction.captureException(e)
            throw e
         } finally {
            transaction.end()
         }  
    }
    

Adding below line for better search result for other developers.
How to add interceptor on starting and ending on each request in ktor. Example of ApplicationCallPipeline.Monitoring and proceed()
4

1 回答 1

2

您可以使用proceed执行管道其余部分的方法来捕获任何发生的异常并完成事务:

intercept(ApplicationCallPipeline.Monitoring) {
    val transaction: Transaction = ElasticApm.startTransaction()
    try {
        transaction.setName("MyTransaction#getApi")
        transaction.setType(Transaction.TYPE_REQUEST)
        proceed() // This will call the rest of a pipeline
    } catch (e: Exception) {
        transaction.captureException(e)
        throw e
    } finally {
        transaction.end()
    }
}

此外,您可以使用属性在调用期间存储事务(从请求开始时开始,在响应发送后结束)。

于 2021-07-08T11:57:29.017 回答