On this page
Series Posts

· 2 min read Posted by Jigar Brahmbhatt

Logger.i() Not Your Style? Customize Kermit Logger!

Discover the simplicity of custom logging with Kermit. This article shows you how to personalize Kermit Logger, making your Kotlin Multiplatform logging experience uniquely yours
Image from https://unsplash.com/photos/F2WX4BTIkpQ
Credit: Image from https://unsplash.com/photos/F2WX4BTIkpQ

In the realm of Kotlin Multiplatform logging, the Kermit library stands as a trusted companion for developers. However, some find its conventional logger.i syntax less appealing. What if you could improve your logging experience with a touch of personalization? Enter the world of custom logger, where logger.info becomes a reality.

Diving into Custom Logging

The journey begins with a glance at a custom code snippet that transforms the Kermit logging experience. This code introduces a custom Logger class adorned with methods like info, and error—a testament to the flexibility Kermit provides for tailoring logging to your liking.

Note that example code below is a very toned down version of full Logger API. It helps with keeping the code minimal while still delivering the idea behind it.

import co.touchlab.kermit.BaseLogger
import co.touchlab.kermit.LoggerConfig
import co.touchlab.kermit.Severity
import co.touchlab.kermit.mutableLoggerConfigInit
import co.touchlab.kermit.platformLogWriter

open class Logger(
    config: LoggerConfig,
    open val tag: String = "MyDefaultTag"
) : BaseLogger(config) {
    inline fun info(throwable: Throwable? = null, tag: String = this.tag, message: () -> String) {
        logBlock(Info, tag, throwable, message)
    }

    inline fun error(throwable: Throwable? = null, tag: String = this.tag, message: () -> String) {
        logBlock(Error, tag, throwable, message)
    }

    inline fun info(messageString: String, throwable: Throwable? = null, tag: String = this.tag) {
        log(Info, tag, throwable, messageString)
    }

    inline fun error(messageString: String, throwable: Throwable? = null, tag: String = this.tag) {
        log(Error, tag, throwable, messageString)
    }

    companion object : Logger(mutableLoggerConfigInit(listOf(platformLogWriter())))
}

Now instead of calling Kermit’s API, you can call your own methods.

Call

Logger.info(...)

rather than

Logger.i(...)

Kermit-core

This flexiblity comes from the modularized kermit components. If you prefer to have custom logger then you need to only depends on kermit-core instead of kermit

implementation "co.touchlab:kermit-core:2.0.4"

Beyond syntax preferences, custom logger methods may include more flexibility matching your application’s unique needs.

Embrace the power of custom logging with Kermit, and let your logs echo your coding identity. Happy logging!