TwitterServer 中的空指标

Empty metrics in TwitterServer

我正在尝试 运行 一个简单的 TwitterServer,其实现来自 https://twitter.github.io/twitter-server/Features.html

在多次请求 http://localhost:9990/echo 之后,我没有在 http://localhost:9990/admin/metrics 中看到任何指标。调试后发现实际的StatsReceiverNullStatsReceiver。我没有在文档中找到任何提及 StatsReceiver 配置的内容。

那么如何更改默认值 NullStatsReceiver

import com.twitter.conversions.time._
import com.twitter.finagle.http.{HttpMuxer, Request, Response, Status}
import com.twitter.finagle.Service
import com.twitter.logging.Formatter
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future, Time}
import java.net.InetSocketAddress

object AdvancedServer extends TwitterServer {

  val what = flag("what", "hello", "String to return")
  val addr = flag("bind", new InetSocketAddress(0), "Bind address")
  val durations = flag("alarms", (1.second, 5.second), "2 alarm durations")
  val counter = statsReceiver.counter("requests_counter")
  override def defaultFormatter = new Formatter(
    timezone = Some("UTC"),
    prefix = "<yyyy-MM-dd HH:mm:ss.SSS> [%.3s] %s: "
  )
  override def failfastOnFlagsNotParsed: Boolean = true

  val service = new Service[Request, Response] {
    def apply(request: Request) = {
      log.debug("Received a request at " + Time.now)
      counter.incr()
      val response = Response(request.version, Status.Ok)
      response.contentString = what() + "\n"
      Future.value(response)
    }
  }

  def main() {
    // We could create a new http server but in this case we use the
    // one already started for /admin/* endpoints.
    // The `TwitterServer` trait exposes an `adminHttpServer` that serve all routes
    // registered in the HttpMuxer object, we just have to add our own.
    HttpMuxer.addHandler("/echo", service)
    HttpMuxer.addHandler("/echo/", service)
    // And wait on the server
    Await.ready(adminHttpServer)
  }
}

我想我已经找到解决办法了。 首先需要添加 finagle-stats 依赖。我用过 v6.43.0。 其次需要将计数器定义为

val counter = MetricsStatsReceiver.defaultRegistry.createCounter("requests_counter").

然后它将按预期工作。