From 92722b0fef92583456101b61261c707ace949829 Mon Sep 17 00:00:00 2001 From: Fabrice Lecomte Date: Wed, 19 Feb 2020 12:46:39 +0100 Subject: [PATCH] Improve SQL log message --- .../fr/postgresjson/connexion/Connection.kt | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/fr/postgresjson/connexion/Connection.kt b/src/main/kotlin/fr/postgresjson/connexion/Connection.kt index 37b1ea1..000f0cd 100644 --- a/src/main/kotlin/fr/postgresjson/connexion/Connection.kt +++ b/src/main/kotlin/fr/postgresjson/connexion/Connection.kt @@ -6,12 +6,13 @@ import com.github.jasync.sql.db.QueryResult import com.github.jasync.sql.db.pool.ConnectionPool import com.github.jasync.sql.db.postgresql.PostgreSQLConnection import com.github.jasync.sql.db.postgresql.PostgreSQLConnectionBuilder +import com.github.jasync.sql.db.util.length import fr.postgresjson.entity.EntityI import fr.postgresjson.entity.Serializable import fr.postgresjson.serializer.Serializer import fr.postgresjson.utils.LoggerDelegate import org.slf4j.Logger -import java.util.concurrent.CompletableFuture +import java.util.concurrent.* typealias SelectOneCallback = QueryResult.(T?) -> Unit typealias SelectCallback = QueryResult.(List) -> Unit @@ -248,15 +249,33 @@ class Connection( data class ParametersQuery(val sql: String, val parameters: List) private fun stopwatchQuery(sql: String, values: List = emptyList(), callback: () -> T): T { - val sqlForLog = "\n${sql.prependIndent()}" try { val start = System.currentTimeMillis() val result = callback() val duration = (System.currentTimeMillis() - start) - logger?.debug("$duration ms for query: $sqlForLog \n {}", values.joinToString(", ")) + val resultText = when (result) { + null -> "with no result" + is QueryResult -> result.rows.firstOrNull()?.joinToString(", ")?.let { text -> + if (text.length > 100) "${text.take(100)}... (size: ${text.length})" else text + } ?: "with no result" + else -> "unknown" + } + val args = """ + |Query ($duration ms): + |${sql.trimIndent().prependIndent()} + |Arguments (${values.length}): + |${values.joinToString("\n").ifBlank { "No arguments" }.prependIndent()} + |Result: + |${resultText.trimIndent().prependIndent()} + """.trimMargin().prependIndent(" > ") + logger?.debug("Query executed in $duration ms \n{}", args) return result } catch (e: Throwable) { - logger?.info("Query Error: $sqlForLog, $values", e) + logger?.info(""" + Query Error: + ${sql.prependIndent()}, + ${values.joinToString(", ").prependIndent()} + """.trimIndent(), e) throw e } }