Last active
October 4, 2024 06:35
-
-
Save joost-de-vries/86a20e2e0659c94e3e6acb5e3a0c62d0 to your computer and use it in GitHub Desktop.
micrometer record Kotlin coroutine suspend functions
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
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