just wanted to share this little cool snippet. Sup...
# coroutines
a
just wanted to share this little cool snippet. Super easy to add a very simple homemade function that logs an error if a database query (or any async operation, really) takes more than 10 seconds 🙂 Coroutines ftw!
Copy code
suspend fun <T> CoroutineScope.logSlowQueries(
    timeoutSeconds: Long?,
    block: suspend () -> T
): T {
    val slowQueryDetectorJob = async {
        delay(Duration.ofSeconds(timeoutSeconds ?: 10))
        val otelCtx = Span.current().spanContext

        if (otelCtx.isValid) {
            log.error("Query not completed after $timeoutSeconds seconds - traceId=${otelCtx.traceId} spanId=${otelCtx.spanId}")
        } else {
            log.error("Query not completed after $timeoutSeconds seconds - NO OTEL CTX AVAILABLE")
        }
    }

    return try {
        block()
    } finally {
        slowQueryDetectorJob.cancel()
    }
}
mother of god 1