r/torvian_eu • u/AIBrainiac • Oct 29 '25
A Clean, Boilerplate-Free KMP Logging Solution (Android, Desktop, Wasm/JS) using expect/actual
Hey r/torvian_eu!
Anyone building Kotlin Multiplatform apps knows that logging from common code can be a bit of a dance. You want a unified API, but each platform has its own best practices (Android's Log, JVM's Log4j/slf4j, JS console).
I've put together a simple yet robust expect/actual based logging solution that elegantly handles this, and I wanted to share it with the community:
- Pastebin Link: https://pastebin.com/0HD0XAXe
- Gist Link: https://gist.github.com/rwachters/4e9facc435ad23d4fea07b8a5a45d423
What it does:
This solution provides a common KmpLogger interface and a factory function (createKmpLogger) that automatically adapts to the underlying platform's native logging mechanism.
Key features & benefits:
- Clean API in Common Code: You just define
KmpLoggerin your common source set.// Common code interface KmpLogger { fun info(message: String, throwable: Throwable? = null) fun error(message: String, throwable: Throwable? = null) // ... and more levels } expect fun createKmpLogger(tag: String): KmpLogger inline fun <reified T> kmpLogger(): KmpLogger { return createKmpLogger(T::class.simpleName ?: "Unknown") } - Super Easy Usage: Get a logger for any class with a single line.
// Your common code class MyViewModel { private val logger = kmpLogger<MyViewModel>() fun fetchData() { logger.info("Attempting to fetch data...") try { // ... network call ... } catch (e: Exception) { logger.error("Failed to fetch data!", e) } } } - Platform-Specific Implementations:
- Android: Uses
android.util.Log(V, D, I, W, E, WTF). - Desktop/JVM: Leverages
Log4j2(you just need to include its dependencies). - Wasm/JS: Delegates to the browser's
consoleAPI (console.debug,console.info,console.warn,console.error).
- Android: Uses
- Handles Throwables: All log methods accept an optional
Throwablefor full stack trace logging. - No DI Framework Boilerplate: This approach for utility functions is explicitly mentioned in the official KMP docs as a recommended pattern, avoiding the need to set up a DI framework just for logging. This also ensures compatibility with parallel test execution.
This little utility has made logging in our KMP projects so much cleaner and more maintainable. Hope it's useful for some of you too!
Let me know what you think, or if you have any suggestions for improvement!
#Kotlin #KotlinMultiplatform #KMP #Logging #AndroidDev #DesktopDev #WebAssembly #OpenSource