diff --git a/src/directMain/kotlin/io/github/oshai/kotlinlogging/Formatter.kt b/src/directMain/kotlin/io/github/oshai/kotlinlogging/Formatter.kt index ab92ac5..66d7a6b 100644 --- a/src/directMain/kotlin/io/github/oshai/kotlinlogging/Formatter.kt +++ b/src/directMain/kotlin/io/github/oshai/kotlinlogging/Formatter.kt @@ -29,16 +29,13 @@ public class DefaultMessageFormatter(private val includePrefix: Boolean = true) } } - private fun Throwable?.throwableToString(): String { - if (this == null) { - return "" - } - var msg = "" - var current = this - while (current != null && current.cause != current) { - msg += ", Caused by: '${current.message}'" - current = current.cause + private fun Throwable?.throwableToString() = createThrowableMsg("", this) + + private tailrec fun createThrowableMsg(msg: String, throwable: Throwable?): String { + return if (throwable == null || throwable.cause == throwable) { + msg + } else { + createThrowableMsg("$msg, Caused by: '${throwable.message}'", throwable.cause) } - return msg } } diff --git a/src/jsTest/kotlin/io/github/oshai/kotlinlogging/SimpleJsTest.kt b/src/jsTest/kotlin/io/github/oshai/kotlinlogging/SimpleJsTest.kt index deb4da6..2fb3e16 100644 --- a/src/jsTest/kotlin/io/github/oshai/kotlinlogging/SimpleJsTest.kt +++ b/src/jsTest/kotlin/io/github/oshai/kotlinlogging/SimpleJsTest.kt @@ -28,6 +28,16 @@ class SimpleJsTest { assertEquals("info", appender.lastLevel) } + @Test + fun logThrowableTest() { + val errorLog = "Something Bad Happened" + val outerMessage = "Outer Message" + val innerMessage = "Inner Message" + val throwable = Throwable(message = outerMessage, cause = Throwable(message = innerMessage)) + logger.error(throwable) { errorLog } + assertEquals("ERROR: [SimpleJsTest] $errorLog, Caused by: '$outerMessage', Caused by: '$innerMessage'", appender.lastMessage) + } + @Test fun offLevelJsTest() { KotlinLoggingConfiguration.LOG_LEVEL = Level.OFF