Created
August 9, 2017 14:42
-
-
Save jeroenr/54211a00221c9a6f9633386e73fbe7aa to your computer and use it in GitHub Desktop.
Trace a REST call with Kamon with OpenTracing support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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