Skip to content

Commit 64edff9

Browse files
committed
add js delegate
used by private val logger by KotlinLogging.logger()
1 parent 2682371 commit 64edff9

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package io.github.oshai
2+
3+
import kotlin.properties.ReadOnlyProperty
4+
import kotlin.reflect.KProperty
5+
6+
/**
7+
* The JS way to define a logger without explicit name
8+
* ```
9+
* class MyClass {
10+
* private val logger by KotlinLogging.logger()
11+
* }
12+
* ```
13+
*/
14+
public fun KotlinLogging.logger(): ReadOnlyProperty<Any?, KLogger> = LoggerDelegate()
15+
16+
private class LoggerDelegate : ReadOnlyProperty<Any?, KLogger> {
17+
private lateinit var logger: KLogger
18+
19+
override fun getValue(thisRef: Any?, property: KProperty<*>): KLogger {
20+
if (!::logger.isInitialized) {
21+
logger =
22+
thisRef.asDynamic()?.constructor?.name.unsafeCast<String?>()?.let {
23+
KotlinLogging.logger(it)
24+
}
25+
?: KotlinLogging.logger("root-logger")
26+
}
27+
return logger
28+
}
29+
}

src/jsTest/kotlin/io/github/oshai/SimpleJsTest.kt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ class SimpleJsTest {
1818
KotlinLoggingConfiguration.APPENDER = ConsoleOutputAppender
1919
}
2020

21+
@Test
22+
fun loggerNameTest() {
23+
assertEquals("MyClass", MyClass().logger2.name)
24+
}
25+
2126
private fun createAppender(): SimpleAppender = SimpleAppender()
2227

2328
class SimpleAppender : Appender {
@@ -50,3 +55,7 @@ class SimpleJsTest {
5055
}
5156
}
5257
}
58+
59+
class MyClass {
60+
val logger2 by KotlinLogging.logger()
61+
}

0 commit comments

Comments
 (0)