-
-
Notifications
You must be signed in to change notification settings - Fork 112
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refined algorithm to determine the name of the hosting class of an an…
…onymous logger
- Loading branch information
1 parent
c3b55ba
commit 37ea16d
Showing
2 changed files
with
40 additions
and
15 deletions.
There are no files selected for viewing
29 changes: 19 additions & 10 deletions
29
src/wasmJsMain/kotlin/io/github/oshai/kotlinlogging/internal/KLoggerNameResolver.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,27 @@ | ||
package io.github.oshai.kotlinlogging.internal | ||
|
||
private const val NO_CLASS = "" | ||
|
||
internal actual object KLoggerNameResolver { | ||
private val kotlinLoggingRegex = Regex("\\.KotlinLogging\\.logger\\s") | ||
private val topLevelPropertyRegex = Regex("<init properties (\\S+)\\.kt>") | ||
private val classPropertyRegex = Regex("\\.(\\S+)\\.<init>") | ||
|
||
internal actual fun name(func: () -> Unit): String { | ||
var found = false | ||
val exception = Exception() | ||
for (line in exception.stackTraceToString().split("\n")) { | ||
if (found) { | ||
return line.substringBefore(".kt").substringAfterLast(".").substringAfterLast("/") | ||
} | ||
if (line.contains("at KotlinLogging")) { | ||
found = true | ||
} | ||
val stackTrace = Exception().stackTraceToString().split("\n") | ||
val invokingClassLine = stackTrace.indexOfFirst(kotlinLoggingRegex::containsMatchIn) + 1 | ||
return if (invokingClassLine in 1 ..< stackTrace.size) { | ||
getInvokingClass(stackTrace[invokingClassLine]) | ||
} else { | ||
NO_CLASS | ||
} | ||
return "" | ||
} | ||
|
||
private fun getInvokingClass(line: String): String { | ||
return topLevelPropertyRegex.find(line)?.let { | ||
it.groupValues[1].split(".").last() | ||
} ?: classPropertyRegex.find(line)?.let { | ||
it.groupValues[1].split(".").last() | ||
} ?: NO_CLASS | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters