Skip to content

Instantly share code, notes, and snippets.

@joost-de-vries
Last active June 14, 2023 12:17
Show Gist options
  • Save joost-de-vries/86a20e2e0659c94e3e6acb5e3a0c62d0 to your computer and use it in GitHub Desktop.
Save joost-de-vries/86a20e2e0659c94e3e6acb5e3a0c62d0 to your computer and use it in GitHub Desktop.
micrometer record Kotlin coroutine suspend functions
class Service(val microMeter: MicroMeterRegistry, val otherService: OtherService){
suspend fun service(id: Long){
recordAsync("theService") { otherService.getTheThing(id) }
}
private suspend fun <A> recordAsync(name: String, block: suspend () -> A): A = metricsRegistry.timer(name)
.recordSuspend(block)
}
suspend fun <A> Timer.recordSuspend(block: suspend () -> A): A =
when (val timer = this) {
is AbstractTimer -> timer.recordSuspendInternal(block)
else -> block()
}
@Suppress("INVISIBLE_MEMBER")
private suspend fun <A> AbstractTimer.recordSuspendInternal(block: suspend () -> A): A {
val s = clock.monotonicTime()
return try {
block()
} finally {
val e = clock.monotonicTime()
record(e - s, TimeUnit.NANOSECONDS)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment