Skip to content

Instantly share code, notes, and snippets.

@jeroenr
Created August 9, 2017 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenr/54211a00221c9a6f9633386e73fbe7aa to your computer and use it in GitHub Desktop.
Save jeroenr/54211a00221c9a6f9633386e73fbe7aa to your computer and use it in GitHub Desktop.
Trace a REST call with Kamon with OpenTracing support
private def uuid = java.util.UUID.randomUUID.toString
def trace = Directive[Unit] {
innerRoute ⇒ ctx ⇒ {
val traceId = s"req-$uuid"
val textMap = readOnlyTextMapFromHeaders(ctx.request.headers)
val incomingSpanContext = Kamon.extract(Format.HttpHeaders, textMap)
val serverSpan = addDefaultTags(Kamon.buildSpan(ctx.request.uri.path.toString))
.asChildOf(incomingSpanContext)
.withSpanTag("myTraceId", traceId)
.startActive()
val innerRouteResult = innerRoute(ctx)(ctx)
innerRouteResult.onComplete(_ => serverSpan.finish())(CallingThreadExecutionContext)
serverSpan.deactivate()
innerRouteResult.map {
case Complete(res) =>
Complete(res.addHeader(RawHeader("x-trace-token", serverSpan.context().traceID.string)))
case o => o
}(CallingThreadExecutionContext)
}
}
def readOnlyTextMapFromHeaders(headers: Seq[HttpHeader]): TextMap = new TextMap {
private val headersMap = headers.map { h => h.name -> h.value }.toMap
override def get(key: String): Option[String] = headersMap.get(key)
override def put(key: String, value: String): Unit = ???
override def values: Iterator[(String, String)] = headersMap.iterator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment