Search code examples
kotlinloggingwhitespace

How to fill with space for pretty logger messages?


Is there a way to fill with spaces after the variable $nameIdDocument so that the 2nd variable (${resultPreventRequest.documentType}) always shows up at the spot ?

I like to have logger messages aligned vertically. I would like to have PASSEPORT and RESIDENCE_PERMIT start at the same position.

Here the code I execute, and the image attached is what is printed by the logger.

LOGGERCTRLONE.info("Correctly Read document | doctype found : $nameIdDocument | ${resultPreventRequest.documentType}")

logger output

I tried the java syntax with %s-20 but it does nothing, regardless where it is positioned.

I have looked up online and there is no subject about this alignment problem in Kotlin.


Solution

  • The Java syntax to use with formatting would be like %-20s. The conversion type, s in this case, always goes last.

    fun main() {
        println("%-25s | %-22s | %s".format("Correctly Read document", "some document.xyz", "some document type"))
        println("%-25s | %-22s | %s".format("Incorrectly Read document", "another document2.xyz", "another document type"))
    }
    

    Prints

    Correctly Read document   | some document.xyz      | some document type
    Incorrectly Read document | another document2.xyz  | another document type
    

    Kotlin doesn't provide any built-in logging feature. The logging library you're using might have a cleaner way to do this.