Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Saturday, September 3, 2016

SLF4J Over Log4j in TornadoFX (Kotlin)

TornadoFX is a JavaFX framework for the Kotlin programming language.  The TornadoFX documentation mentions Java logging, but you can use the popular SLF4J / Log4j combination.


This Gradle build file lists the SLF4J and Log4j dependencies.  SLF4J requires the API for compiling and a connector "Log4J-slf4j-impl".  Log4j-api and log4j-core are Log4j2 libraries.

group 'com.bekwam'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.0.3'

    repositories {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

apply plugin: 'java'
apply plugin: 'kotlin'

sourceCompatibility = 1.8

repositories {

dependencies {

    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile 'no.tornado:tornadofx:1.5.5'
    compile 'org.slf4j:slf4j-api:1.7.21'
    compile 'org.apache.logging.log4j:log4j-slf4j-impl:2.6.2'
    compile 'org.apache.logging.log4j:log4j-api:2.6.2'
    compile 'org.apache.logging.log4j:log4j-core:2.6.2'

    testCompile group: 'junit', name: 'junit', version: '4.11'

Log4j Configuration

Put this file "log4j2.xml" on the classpath.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        <Root level="debug">
            <AppenderRef ref="Console"/>

Usage in Kotlin

Finally, import the library and add a class variable "logger".  Then, in your functions you can use a shorter version of isDebugEnabled that reduces the amount of semicolons, curly braces, and parenthesis.

import javafx.scene.layout.VBox
import tornadofx.App
import tornadofx.View
import org.slf4j.LoggerFactory

class MainWindow : View() {

    var logger = LoggerFactory.getLogger(MainWindow::class.java)

    override val root: VBox by fxml()

    init {

        if( logger.isDebugEnabled )


    fun exitApp() {

        if( logger.isDebugEnabled )
            logger.debug("[EXIT APP]")


    fun lookupUser() {
        if( logger.isDebugEnabled )
            logger.debug("[LOOKUP USER]")

class BKCourseApp : App(MainWindow::class)

When started, the app has a menu with items for Exit and Lookup User.  With the current configuration, this code will log a message to the console when an action is triggered.

No comments:

Post a Comment