Created
March 27, 2023 11:18
-
-
Save monosoul/6f12175c5b898ed9676b7387cc07d353 to your computer and use it in GitHub Desktop.
DataDog Tracing utils for Kotlin coroutines
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
dependencies { | |
implementation("com.datadoghq:dd-trace-ot:1.10.1") // make sure the version here is aligned with DD Java agent | |
} |
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
import datadog.trace.api.DDTags | |
import io.opentracing.Span | |
import io.opentracing.Tracer | |
import io.opentracing.log.Fields | |
import io.opentracing.tag.Tags | |
import io.opentracing.util.GlobalTracer | |
suspend fun <T : Any, O> T.coRunTraced( | |
methodName: String, | |
block: suspend T.(Span) -> O, | |
): O = coRunTraced(resource = "${javaClass.simpleName}.$methodName", block = block) | |
fun <T : Any, O> T.runTraced( | |
methodName: String, | |
block: T.(Span) -> O, | |
): O = runTraced(resource = "${javaClass.simpleName}.$methodName", block = block) | |
suspend fun <T, O> T.coRunTraced( | |
resource: String, | |
operation: String = "service.call", | |
block: suspend T.(Span) -> O, | |
): O = inlineRunTraced(operation, resource) { block(it) } | |
fun <T, O> T.runTraced( | |
resource: String, | |
operation: String = "service.call", | |
block: T.(Span) -> O, | |
): O = inlineRunTraced(operation, resource) { block(it) } | |
private inline fun <T, O> T.inlineRunTraced( | |
operation: String, | |
resource: String, | |
block: T.(Span) -> O, | |
): O { | |
val tracer = GlobalTracer.get() | |
val span = tracer.startSpan(operation, resource) | |
return runCatching { | |
tracer.activateSpan(span).use { | |
block(span) | |
} | |
}.onFailure { | |
span.finish(it) | |
}.onSuccess { | |
span.finish() | |
}.getOrThrow() | |
} | |
private fun Tracer.startSpan(operation: String, resource: String): Span = | |
buildSpan(operation).withTag(DDTags.RESOURCE_NAME, resource).start() | |
private fun Span.finish(e: Throwable) { | |
setTag(Tags.ERROR, true) | |
log(mapOf(Fields.ERROR_OBJECT to e)) | |
finish() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment