Skip to content

Commit 27f93f9

Browse files
committed
Fix #160 - throw error instead of show in log
in case system property is defined: kotlin-logging.throwOnMessageError
1 parent 0e47df5 commit 27f93f9

File tree

5 files changed

+54
-1
lines changed

5 files changed

+54
-1
lines changed

src/commonMain/kotlin/mu/internal/MessageInvoker.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ internal inline fun (() -> Any?).toStringSafe(): String {
55
return try {
66
invoke().toString()
77
} catch (e: Exception) {
8-
"Log message invocation failed: $e"
8+
ErrorMessageProducer.getErrorLog(e)
99
}
1010
}
11+
12+
public expect object ErrorMessageProducer {
13+
public fun getErrorLog(e: Exception): String
14+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package mu.internal
2+
3+
public actual object ErrorMessageProducer {
4+
public actual fun getErrorLog(e: Exception): String = "Log message invocation failed: $e"
5+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package mu.internal
2+
3+
public actual object ErrorMessageProducer {
4+
public actual fun getErrorLog(e: Exception): String {
5+
if (System.getProperties().containsKey("kotlin-logging.throwOnMessageError")) {
6+
throw e
7+
} else {
8+
return "Log message invocation failed: $e"
9+
}
10+
}
11+
12+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package mu.internal
2+
3+
import org.junit.Test
4+
import kotlin.test.assertEquals
5+
6+
class MessageInvokerJavaTest {
7+
8+
@Test
9+
fun toStringSafeChecks() {
10+
assertEquals("hi", { "hi" }.toStringSafe())
11+
}
12+
13+
@Test
14+
fun toStringSafeChecksThrowException() {
15+
assertEquals("Log message invocation failed: java.lang.Exception: hi", { throw Exception("hi") }.toStringSafe())
16+
}
17+
18+
@Test(expected = Exception::class)
19+
fun toStringSafeChecksThrowExceptionWithSystemProperty() {
20+
System.setProperty("kotlin-logging.throwOnMessageError", "")
21+
try {
22+
{ throw Exception("hi") }.toStringSafe()
23+
} finally {
24+
System.clearProperty("kotlin-logging.throwOnMessageError")
25+
}
26+
}
27+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package mu.internal
2+
3+
public actual object ErrorMessageProducer {
4+
public actual fun getErrorLog(e: Exception): String = "Log message invocation failed: $e"
5+
}

0 commit comments

Comments
 (0)