diff options
Diffstat (limited to 'kamon-play/src')
9 files changed, 373 insertions, 88 deletions
diff --git a/kamon-play/src/main/resources/META-INF/aop.xml b/kamon-play/src/main/resources/META-INF/aop.xml index ca499a33..e24d48d5 100644 --- a/kamon-play/src/main/resources/META-INF/aop.xml +++ b/kamon-play/src/main/resources/META-INF/aop.xml @@ -4,6 +4,7 @@ <aspects> <aspect name="kamon.play.instrumentation.RequestInstrumentation"/> <aspect name="kamon.play.instrumentation.WSInstrumentation"/> + <aspect name="kamon.play.instrumentation.LoggerLikeInstrumentation"/> </aspects> <weaver> diff --git a/kamon-play/src/main/resources/reference.conf b/kamon-play/src/main/resources/reference.conf index 47a31ef4..72266a0c 100644 --- a/kamon-play/src/main/resources/reference.conf +++ b/kamon-play/src/main/resources/reference.conf @@ -3,6 +3,10 @@ # ================================== # kamon { + metrics { + tick-interval = 1 hour + } + play { include-trace-token-header = true trace-token-header-name = "X-Trace-Token" diff --git a/kamon-play/src/main/scala/kamon/play/Play.scala b/kamon-play/src/main/scala/kamon/play/Play.scala index ca9c10e5..03436458 100644 --- a/kamon-play/src/main/scala/kamon/play/Play.scala +++ b/kamon-play/src/main/scala/kamon/play/Play.scala @@ -18,6 +18,8 @@ package kamon.play import akka.actor.{ ExtendedActorSystem, Extension, ExtensionIdProvider, ExtensionId } import kamon.Kamon +import kamon.http.HttpServerMetrics +import kamon.metric.Metrics object Play extends ExtensionId[PlayExtension] with ExtensionIdProvider { override def lookup(): ExtensionId[_ <: Extension] = Play @@ -29,6 +31,7 @@ class PlayExtension(private val system: ExtendedActorSystem) extends Kamon.Exten private val config = system.settings.config.getConfig("kamon.play") + val httpServerMetrics = Kamon(Metrics)(system).register(HttpServerMetrics, HttpServerMetrics.Factory).get val defaultDispatcher = system.dispatchers.lookup(config.getString("dispatcher")) val includeTraceToken: Boolean = config.getBoolean("include-trace-token-header") val traceTokenHeaderName: String = config.getString("trace-token-header-name") diff --git a/kamon-play/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala b/kamon-play/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala new file mode 100644 index 00000000..b7afeb76 --- /dev/null +++ b/kamon-play/src/main/scala/kamon/play/instrumentation/LoggerLikeInstrumentation.scala @@ -0,0 +1,70 @@ +/* ========================================================================================= + * Copyright © 2013-2014 the kamon project <http://kamon.io/> + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + * ========================================================================================= + */ + +package kamon.play.instrumentation + +import kamon.trace.{ TraceContext, TraceContextAware } +import org.aspectj.lang.ProceedingJoinPoint +import org.aspectj.lang.annotation._ +import org.slf4j.MDC + +@Aspect +class LoggerLikeInstrumentation { + + import LoggerLikeInstrumentation._ + + @DeclareMixin("play.api.LoggerLike+") + def mixinContextAwareToLoggerLike: TraceContextAware = TraceContextAware.default + + @Pointcut("execution(* play.api.LoggerLike+.info(..))") + def infoPointcut(): Unit = {} + + @Pointcut("execution(* play.api.LoggerLike+.warn(..))") + def warnPointcut(): Unit = {} + + @Pointcut("execution(* play.api.LoggerLike+.error(..))") + def errorPointcut(): Unit = {} + + @Pointcut("execution(* play.api.LoggerLike+.trace(..))") + def tracePointcut(): Unit = {} + + @Around("(infoPointcut() || warnPointcut() || errorPointcut() || tracePointcut()) && this(logger)") + def aroundLog(pjp: ProceedingJoinPoint, logger: TraceContextAware): Any = { + withMDC(logger.traceContext) { + pjp.proceed() + } + } +} + +object LoggerLikeInstrumentation { + def withMDC[A](currentContext: Option[TraceContext])(block: ⇒ A): A = { + val keys = currentContext.map(extractProperties).map(putAndExtractKeys) + + try block finally keys.map(k ⇒ k.foreach(MDC.remove(_))) + } + + def putAndExtractKeys(values: Iterable[Map[String, Any]]): Iterable[String] = values.map { + value ⇒ value.map { case (key, value) ⇒ MDC.put(key, value.toString); key } + }.flatten + + def extractProperties(ctx: TraceContext): Iterable[Map[String, Any]] = ctx.traceLocalStorage.underlyingStorage.values.map { + case traceLocalValue @ (p: Product) ⇒ { + val properties = p.productIterator + traceLocalValue.getClass.getDeclaredFields.filter(field ⇒ field.getName != "$outer").map(_.getName -> properties.next).toMap + } + case anything ⇒ Map.empty[String, Any] + } +} + diff --git a/kamon-play/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala b/kamon-play/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala index 00170b1b..3247fcc9 100644 --- a/kamon-play/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala +++ b/kamon-play/src/main/scala/kamon/play/instrumentation/RequestInstrumentation.scala @@ -1,23 +1,22 @@ -/* =================================================== +/* ========================================================================================= * Copyright © 2013-2014 the kamon project <http://kamon.io/> * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ========================================================== */ + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + * ========================================================================================= + */ package kamon.play.instrumentation import kamon.Kamon -import kamon.play.Play +import kamon.play.{ PlayExtension, Play } import kamon.trace.{ TraceContextAware, TraceRecorder } import org.aspectj.lang.ProceedingJoinPoint import org.aspectj.lang.annotation._ @@ -49,15 +48,21 @@ class RequestInstrumentation { } @Around("execution(* play.api.GlobalSettings+.doFilter(*)) && args(next)") - def afterDoFilter(pjp: ProceedingJoinPoint, next: EssentialAction): Any = { + def aroundDoFilter(pjp: ProceedingJoinPoint, next: EssentialAction): Any = { val essentialAction = (requestHeader: RequestHeader) ⇒ { val incomingContext = TraceRecorder.currentContext - val executor = Kamon(Play)(Akka.system()).defaultDispatcher + val playExtension = Kamon(Play)(Akka.system()) + val executor = playExtension.defaultDispatcher next(requestHeader).map { result ⇒ + TraceRecorder.currentContext.map { ctx ⇒ + recordHttpServerMetrics(result, ctx.name, playExtension) + } + TraceRecorder.finish() + incomingContext match { case None ⇒ result case Some(traceContext) ⇒ @@ -71,6 +76,9 @@ class RequestInstrumentation { pjp.proceed(Array(EssentialAction(essentialAction))) } + def recordHttpServerMetrics(result: SimpleResult, traceName: String, playExtension: PlayExtension): Unit = + playExtension.httpServerMetrics.recordResponse(traceName, result.header.status.toString, 1L) + @Around("execution(* play.api.GlobalSettings+.onError(..)) && args(request, ex)") def aroundOnError(pjp: ProceedingJoinPoint, request: TraceContextAware, ex: Throwable): Any = request.traceContext match { case None ⇒ pjp.proceed() diff --git a/kamon-play/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala b/kamon-play/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala index f9e01471..b9f09111 100644 --- a/kamon-play/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala +++ b/kamon-play/src/main/scala/kamon/play/instrumentation/WSInstrumentation.scala @@ -19,7 +19,7 @@ package kamon.play.instrumentation import org.aspectj.lang.annotation.{ Around, Pointcut, Aspect } import org.aspectj.lang.ProceedingJoinPoint import kamon.trace.TraceRecorder -import kamon.metrics.TraceMetrics.HttpClientRequest +import kamon.metric.TraceMetrics.HttpClientRequest import play.api.libs.ws.WS.WSRequest import scala.concurrent.Future import play.api.libs.ws.Response @@ -36,7 +36,7 @@ class WSInstrumentation { def aroundExecuteRequest(pjp: ProceedingJoinPoint, request: WSRequest): Any = { import WSInstrumentation._ - val completionHandle = TraceRecorder.startSegment(HttpClientRequest(request.url, UserTime), basicRequestAttributes(request)) + val completionHandle = TraceRecorder.startSegment(HttpClientRequest(request.url), basicRequestAttributes(request)) val response = pjp.proceed().asInstanceOf[Future[Response]] @@ -50,7 +50,6 @@ class WSInstrumentation { } object WSInstrumentation { - val UserTime = "UserTime" def basicRequestAttributes(request: WSRequest): Map[String, String] = { Map[String, String]( diff --git a/kamon-play/src/test/scala/kamon/play/LoggerLikeInstrumentationSpec.scala b/kamon-play/src/test/scala/kamon/play/LoggerLikeInstrumentationSpec.scala new file mode 100644 index 00000000..c41f7004 --- /dev/null +++ b/kamon-play/src/test/scala/kamon/play/LoggerLikeInstrumentationSpec.scala @@ -0,0 +1,122 @@ +/* ========================================================================================= + * Copyright © 2013-2014 the kamon project <http://kamon.io/> + * + * Licensed under the Apache License, Version 2.0 (the "License") you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + * ========================================================================================= + */ + +package kamon.play + +import ch.qos.logback.classic.spi.ILoggingEvent +import ch.qos.logback.classic.{ AsyncAppender, LoggerContext } +import ch.qos.logback.core.read.ListAppender +import ch.qos.logback.core.status.NopStatusListener +import kamon.trace.TraceLocal +import org.scalatest.BeforeAndAfter +import org.scalatestplus.play._ +import org.slf4j +import play.api.LoggerLike +import play.api.mvc.Results.Ok +import play.api.mvc._ +import play.api.test.Helpers._ +import play.api.test._ + +import scala.concurrent.Future + +class LoggerLikeInstrumentationSpec extends PlaySpec with OneServerPerSuite with BeforeAndAfter { + + System.setProperty("config.file", "./kamon-play/src/test/resources/conf/application.conf") + + val executor = scala.concurrent.ExecutionContext.Implicits.global + + val infoMessage = "Info Message" + val headerValue = "My header value" + val otherValue = "My other value" + + case class LocalStorageValue(header: String, other: String) + + object TraceLocalKey extends TraceLocal.TraceLocalKey { + type ValueType = LocalStorageValue + } + + before { + LoggingHandler.startLogging() + } + + after { + LoggingHandler.stopLogging() + } + + implicit override lazy val app = FakeApplication(withRoutes = { + + case ("GET", "/logging") ⇒ + Action.async { + Future { + TraceLocal.store(TraceLocalKey)(LocalStorageValue(headerValue, otherValue)) + LoggingHandler.info(infoMessage) + Ok("OK") + }(executor) + } + }) + + "the LoggerLike instrumentation" should { + "be put the properties of TraceLocal into the MDC as key -> value in a request" in { + LoggingHandler.appenderStart() + + val Some(result) = route(FakeRequest(GET, "/logging")) + Thread.sleep(500) // wait to complete the future + TraceLocal.retrieve(TraceLocalKey) must be(Some(LocalStorageValue(headerValue, otherValue))) + + LoggingHandler.appenderStop() + + headerValue must be(LoggingHandler.getValueFromMDC("header")) + otherValue must be(LoggingHandler.getValueFromMDC("other")) + } + } +} + +object LoggingHandler extends LoggerLike { + + val loggerContext = new LoggerContext() + val rootLogger = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) + val asyncAppender = new AsyncAppender() + val listAppender = new ListAppender[ILoggingEvent]() + val nopStatusListener = new NopStatusListener() + + override val logger: slf4j.Logger = rootLogger + + def startLogging(): Unit = { + loggerContext.getStatusManager().add(nopStatusListener) + asyncAppender.setContext(loggerContext) + listAppender.setContext(loggerContext) + listAppender.setName("list") + listAppender.start() + } + + def stopLogging(): Unit = { + listAppender.stop() + } + + def appenderStart(): Unit = { + asyncAppender.addAppender(listAppender) + asyncAppender.start() + rootLogger.addAppender(asyncAppender) + } + + def appenderStop(): Unit = { + asyncAppender.stop() + } + + def getValueFromMDC(key: String): String = { + listAppender.list.get(0).getMDCPropertyMap.get(key) + } +} + diff --git a/kamon-play/src/test/scala/kamon/play/RequestInstrumentationSpec.scala b/kamon-play/src/test/scala/kamon/play/RequestInstrumentationSpec.scala index 1ba82dc5..eff6f280 100644 --- a/kamon-play/src/test/scala/kamon/play/RequestInstrumentationSpec.scala +++ b/kamon-play/src/test/scala/kamon/play/RequestInstrumentationSpec.scala @@ -1,43 +1,49 @@ -/* =================================================== +/* ========================================================================================= * Copyright © 2013-2014 the kamon project <http://kamon.io/> * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ========================================================== */ + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. + * ========================================================================================= + */ package kamon.play -import play.api.test._ -import play.api.mvc.{ Results, Action } -import play.api.mvc.Results.Ok -import scala.Some -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future -import org.junit.runner.RunWith -import org.specs2.runner.JUnitRunner -import play.api.test.FakeApplication +import scala.concurrent.duration._ +import kamon.Kamon +import kamon.http.HttpServerMetrics +import kamon.metric.{ CollectionContext, Metrics } import kamon.play.action.TraceName +import kamon.trace.{ TraceLocal, TraceRecorder } +import org.scalatestplus.play._ +import play.api.libs.concurrent.Execution.Implicits.defaultContext +import play.api.mvc.Results.Ok +import play.api.mvc._ +import play.api.test.Helpers._ +import play.api.test._ +import play.libs.Akka -@RunWith(classOf[JUnitRunner]) -class RequestInstrumentationSpec extends PlaySpecification { +import scala.concurrent.{ Await, Future } + +class RequestInstrumentationSpec extends PlaySpec with OneServerPerSuite { System.setProperty("config.file", "./kamon-play/src/test/resources/conf/application.conf") - def appWithRoutes = FakeApplication(withRoutes = { + val executor = scala.concurrent.ExecutionContext.Implicits.global + + implicit override lazy val app = FakeApplication(withGlobal = Some(MockGlobalTest), withRoutes = { + case ("GET", "/async") ⇒ Action.async { Future { Ok("Async.async") - } + }(executor) } case ("GET", "/notFound") ⇒ Action { @@ -56,41 +62,94 @@ class RequestInstrumentationSpec extends PlaySpecification { Action.async { Future { Ok("Async.async") - } + }(executor) } } + case ("GET", "/retrieve") ⇒ + Action { + Ok("retrieve from TraceLocal") + } }) private val traceTokenValue = "kamon-trace-token-test" private val traceTokenHeaderName = "X-Trace-Token" private val expectedToken = Some(traceTokenValue) private val traceTokenHeader = traceTokenHeaderName -> traceTokenValue + private val traceLocalStorageValue = "localStorageValue" + private val traceLocalStorageKey = "localStorageKey" + private val traceLocalStorageHeader = traceLocalStorageKey -> traceLocalStorageValue "the Request instrumentation" should { - "respond to the Async Action with X-Trace-Token" in new WithServer(appWithRoutes) { - val Some(result) = route(FakeRequest(GET, "/async").withHeaders(traceTokenHeader)) - header(traceTokenHeaderName, result) must equalTo(expectedToken) + "respond to the Async Action with X-Trace-Token" in { + val Some(result) = route(FakeRequest(GET, "/async").withHeaders(traceTokenHeader, traceLocalStorageHeader)) + header(traceTokenHeaderName, result) must be(expectedToken) } - "respond to the NotFound Action with X-Trace-Token" in new WithServer(appWithRoutes) { + "respond to the NotFound Action with X-Trace-Token" in { val Some(result) = route(FakeRequest(GET, "/notFound").withHeaders(traceTokenHeader)) - header(traceTokenHeaderName, result) must equalTo(expectedToken) + header(traceTokenHeaderName, result) must be(expectedToken) } - "respond to the Default Action with X-Trace-Token" in new WithServer(appWithRoutes) { + "respond to the Default Action with X-Trace-Token" in { val Some(result) = route(FakeRequest(GET, "/default").withHeaders(traceTokenHeader)) - header(traceTokenHeaderName, result) must equalTo(expectedToken) + header(traceTokenHeaderName, result) must be(expectedToken) } - "respond to the Redirect Action with X-Trace-Token" in new WithServer(appWithRoutes) { + "respond to the Redirect Action with X-Trace-Token" in { val Some(result) = route(FakeRequest(GET, "/redirect").withHeaders(traceTokenHeader)) - header("Location", result) must equalTo(Some("/redirected")) - header(traceTokenHeaderName, result) must equalTo(expectedToken) + header("Location", result) must be(Some("/redirected")) + header(traceTokenHeaderName, result) must be(expectedToken) } - "respond to the Async Action with X-Trace-Token and the renamed trace" in new WithServer(appWithRoutes) { + "respond to the Async Action with X-Trace-Token and the renamed trace" in { val Some(result) = route(FakeRequest(GET, "/async-renamed").withHeaders(traceTokenHeader)) - header(traceTokenHeaderName, result) must equalTo(expectedToken) + Thread.sleep(500) // wait to complete the future + TraceRecorder.currentContext.map(_.name) must be(Some("renamed-trace")) + header(traceTokenHeaderName, result) must be(expectedToken) + } + + "propagate the TraceContext and LocalStorage through of filters in the current request" in { + val Some(result) = route(FakeRequest(GET, "/retrieve").withHeaders(traceTokenHeader, traceLocalStorageHeader)) + TraceLocal.retrieve(TraceLocalKey).get must be(traceLocalStorageValue) + } + + "record http server metrics for all processed requests" in { + val collectionContext = CollectionContext(100) + Kamon(Metrics)(Akka.system()).register(HttpServerMetrics, HttpServerMetrics.Factory).get.collect(collectionContext) + + for (repetition ← 1 to 10) { + Await.result(route(FakeRequest(GET, "/default").withHeaders(traceTokenHeader)).get, 10 seconds) + } + + for (repetition ← 1 to 5) { + Await.result(route(FakeRequest(GET, "/notFound").withHeaders(traceTokenHeader)).get, 10 seconds) + } + + val snapshot = Kamon(Metrics)(Akka.system()).register(HttpServerMetrics, HttpServerMetrics.Factory).get.collect(collectionContext) + snapshot.countsPerTraceAndStatusCode("GET: /default")("200").count must be(10) + snapshot.countsPerTraceAndStatusCode("GET: /notFound")("404").count must be(5) + snapshot.countsPerStatusCode("200").count must be(10) + snapshot.countsPerStatusCode("404").count must be(5) } } -}
\ No newline at end of file + + object MockGlobalTest extends WithFilters(TraceLocalFilter) + + object TraceLocalKey extends TraceLocal.TraceLocalKey { + type ValueType = String + } + + object TraceLocalFilter extends Filter { + override def apply(next: (RequestHeader) ⇒ Future[SimpleResult])(header: RequestHeader): Future[SimpleResult] = { + TraceRecorder.withTraceContext(TraceRecorder.currentContext) { + + TraceLocal.store(TraceLocalKey)(header.headers.get(traceLocalStorageKey).getOrElse("unknown")) + + next(header).map { + result ⇒ result.withHeaders((traceLocalStorageKey -> TraceLocal.retrieve(TraceLocalKey).get)) + } + } + } + } +} + diff --git a/kamon-play/src/test/scala/kamon/play/WSInstrumentationSpec.scala b/kamon-play/src/test/scala/kamon/play/WSInstrumentationSpec.scala index b321d123..a9a2d5fa 100644 --- a/kamon-play/src/test/scala/kamon/play/WSInstrumentationSpec.scala +++ b/kamon-play/src/test/scala/kamon/play/WSInstrumentationSpec.scala @@ -1,5 +1,5 @@ /* =================================================== - * Copyright © 2013 2014 the kamon project <http://kamon.io/> + * Copyright © 2013-2014 the kamon project <http://kamon.io/> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,50 +16,69 @@ package kamon.play -import play.api.test._ import play.api.mvc.Action import play.api.mvc.Results.Ok -import scala.Some -import scala.concurrent.ExecutionContext.Implicits.global -import org.junit.runner.RunWith -import org.specs2.runner.JUnitRunner -import play.api.test.FakeApplication import play.api.libs.ws.WS -import scala.util._ -import scala.concurrent.Await -import scala.concurrent.duration._ +import org.scalatestplus.play.OneServerPerSuite +import play.api.test._ +import play.api.test.Helpers._ +import akka.actor.ActorSystem +import akka.testkit.{ TestKitBase, TestProbe } -@RunWith(classOf[JUnitRunner]) -class WSInstrumentationSpec extends PlaySpecification { +import com.typesafe.config.ConfigFactory +import org.scalatest.{ Matchers, WordSpecLike } +import kamon.Kamon +import kamon.metric.{ TraceMetrics, Metrics } +import kamon.metric.Subscriptions.TickMetricSnapshot +import kamon.metric.TraceMetrics.ElapsedTime + +class WSInstrumentationSpec extends TestKitBase with WordSpecLike with Matchers with OneServerPerSuite { System.setProperty("config.file", "./kamon-play/src/test/resources/conf/application.conf") - val appWithRoutes = FakeApplication(withRoutes = { - case ("GET", "/async") ⇒ - Action { - val request = WS.url("http://maps.googleapis.com/maps/api/geocode/json?address=China&sensor=true").get() + implicit lazy val system: ActorSystem = ActorSystem("play-ws-instrumentation-spec", ConfigFactory.parseString( + """ + |akka { + | loglevel = ERROR + |} + | + |kamon { + | metrics { + | tick-interval = 2 seconds + | + | filters = [ + | { + | trace { + | includes = [ "*" ] + | excludes = [] + | } + | } + | ] + | } + |} + """.stripMargin)) - val future = request map { - response ⇒ (response.json \\ "location") - } + implicit override lazy val app = FakeApplication(withRoutes = { + case ("GET", "/async") ⇒ Action { Ok("ok") } + }) - val result = Await.result(future, 10 seconds).asInstanceOf[List[play.api.libs.json.JsObject]] + "the WS instrumentation" should { + "respond to the Async Action and complete the WS request" in { - val latitude = (result(0) \\ "lat")(0).toString - val longitude = (result(0) \\ "lng")(0).toString + val metricListener = TestProbe() + Kamon(Metrics)(system).subscribe(TraceMetrics, "*", metricListener.ref, permanently = true) + metricListener.expectMsgType[TickMetricSnapshot] - Ok(latitude + " " + longitude) - } - }) + val response = await(WS.url("http://localhost:19001/async").get()) + response.status should be(OK) - "the WS instrumentation" should { - "respond to the Async Action and complete the WS request" in new WithServer(appWithRoutes) { - val Some(result) = route(FakeRequest(GET, "/async")) - result.onComplete { - case Success(result) ⇒ result.header.status must equalTo(200) - case Failure(throwable) ⇒ failure(throwable.getMessage) - } - Thread.sleep(2000) //wait to complete the future + // val tickSnapshot = metricListener.expectMsgType[TickMetricSnapshot] + // val traceMetrics = tickSnapshot.metrics.find { case (k, v) ⇒ k.name.contains("async") } map (_._2.metrics) + // traceMetrics should not be empty + // + // traceMetrics map { metrics ⇒ + // metrics(ElapsedTime).numberOfMeasurements should be(1L) + // } } } }
\ No newline at end of file |