|
| 1 | +package io.github.oshai.kotlinlogging.internal |
| 2 | + |
| 3 | +import com.oracle.svm.core.annotate.Substitute |
| 4 | +import com.oracle.svm.core.annotate.TargetClass |
| 5 | +import com.oracle.svm.core.annotate.TargetElement |
| 6 | +import io.github.oshai.kotlinlogging.KLogger |
| 7 | +import io.github.oshai.kotlinlogging.jul.internal.JulLoggerFactory |
| 8 | +import io.github.oshai.kotlinlogging.slf4j.internal.Slf4jLoggerFactory |
| 9 | +import java.util.function.BooleanSupplier |
| 10 | + |
| 11 | +/** |
| 12 | + * This class is a substitution class as described in |
| 13 | + * [https://build-native-java-apps.cc/developer-guide/substitution/]. It fixes an issue where the |
| 14 | + * native build (GraalVM native-image) fails if Logback is not on the classpath. See |
| 15 | + * [https://github.com/oshai/kotlin-logging/issues/465]. The weird-looking class name is according |
| 16 | + * to convention. |
| 17 | + */ |
| 18 | +@Suppress("unused") |
| 19 | +internal class Target_io_github_oshai_kotlinlogging_internal_KLoggerFactory { |
| 20 | + @TargetClass( |
| 21 | + className = "io.github.oshai.kotlinlogging.internal.KLoggerFactory", |
| 22 | + onlyWith = [LogbackNotOnClasspath::class], |
| 23 | + ) |
| 24 | + companion object { |
| 25 | + @Substitute |
| 26 | + @TargetElement(name = "logger\$kotlin_logging") |
| 27 | + fun logger(name: String): KLogger { |
| 28 | + if (System.getProperty("kotlin-logging-to-jul") != null) { |
| 29 | + return JulLoggerFactory.wrapJLogger(JulLoggerFactory.jLogger(name)) |
| 30 | + } |
| 31 | + // Intentionally leave out the logback branch as logback is not on the classpath. |
| 32 | + // default to SLF4J |
| 33 | + return Slf4jLoggerFactory.wrapJLogger(Slf4jLoggerFactory.jLogger(name)) |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +internal class LogbackNotOnClasspath : BooleanSupplier { |
| 39 | + override fun getAsBoolean(): Boolean { |
| 40 | + try { |
| 41 | + Class.forName("ch.qos.logback.classic.LoggerContext") |
| 42 | + return false |
| 43 | + } catch (_: ClassNotFoundException) { |
| 44 | + return true |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments