Log4j in Kotlin

How to add in few steps professional logging support to your kotlin application? Using gradle dependencies there is a way to very quickly add logging support for you. Moreover you are able to use logging in efficient way. Use log4j in Kotlin.


First in your build.gradle add following dependencies that will add log4j to logging.

log_version = '2.7'
kotlinLoggingVersion = '1.4.3'

compile "io.github.microutils:kotlin-logging:$kotlinLoggingVersion"
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: log_version
    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: log_version
    compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: log_version


To assure that logging is efficient you may then use any  util class to provide logging methods to your code.

    val logger = KotlinLogging.logger { }

   fun doSomething(){
		val something = "Any to String parsable"
        logger.info { "Text: $something -  Querying for logs with lenght=${something.length}" }


By using $something you will be able to dynamically add to the output a method invocation of .toString() at object.  To access a field in object simply use: ${something.length} to invoke a .toString() on a field. 

Remember that it is better to use { “….”} then using () while invoking methods on logger. Like logger.info { “…” }




Posted in: Simple How To

Tagged as:

Log4j in Kotlin

Are you using log4j2?

Thank you for the vote!

Leave a Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Notify of