Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leverage tail recursion when creating message out of Throwable #423

Merged
merged 2 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions src/directMain/kotlin/io/github/oshai/kotlinlogging/Formatter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
13 changes: 13 additions & 0 deletions src/jsTest/kotlin/io/github/oshai/kotlinlogging/SimpleJsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ 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
Expand Down
Loading