Hi, when doing <logger.info> { expr } - Can I avoi...
# kotlin-logging
g
Hi, when doing logger.info { expr } - Can I avoid logging
null
? I do not want to do
expr?.<http://logger.info|logger.info> { it }
to avoid calculating the expr whatever the logging level.
s
I don't think such API is built-in anywhere in kotlin-logging library. One thing you can do is create your own class implementing KLogger, which would add null checks after level evaluation but before invoking actual implementation:
Copy code
class NotNullLogger(private val logger: KLogger) : KLogger by logger {
    override fun debug(msg: () -> Any?) {
        if (isDebugEnabled) msg()?.let { logger.debug { it } }
    }
    [...]
}

fun NotNullLogger(func: () -> Unit) = NotNullLogger(KotlinLogging.logger(func))

val logger = NotNullLogger { }
logger.debug { some nullable expression }
👍 1
g
Thank you!