Published on

IntelliJ Live Template to setup the logger

Authors

I love using the IntelliJ IDE. It is my go-to for most heavy dev tasks (for lighter tasks and note-taking I generally use VS Code or/and Spacemacs).

One thing that is always a pain in JVM projects is remembering how to set up your initial logger instance in a class:

  • Do you use the logger factory?
  • Do you use .getLogger? Do you use sl4j or commons?
  • Do I use the classname or a string?

I end up searching for old code or another class that has a logger setup and copy-paste this.

To speed this up, even more, I set up an IntelliJ live template to insert a companion object with the initial shell of the logger. I just need to insert the classname (I cannot work out how to get getClassName() to work under "edit variables"). I configured this against all Kotlin types and used the abbreviation newLogger (change this to whatever makes sense for you). My actual "Template text" is:

companion object {
 private val logger = org.slf4j.LoggerFactory.getLogger($END$::class.java)
}

Note:

  • I use the fully qualified class name so that IntelliJ knows which LoggerFactory to use - it will automatically unqualify it and add this as an import.
  • ENDEND is a special variable in live templates that tells the template where to leave the cursor once the template has been generated.
  • I place this in a companion object as this is the Kotlin equivalent of making something static.