Java › Swing

Adding SLF4J and Logback to a Java Swing app

Replace Swing console prints with SLF4J 2 and Logback, including provider resolution, rolling files, log levels, and deferred formatting.

Adding SLF4J and Logback to a Java Swing app

My Swing project used System.out.println() for diagnostics and status updates. I moved those calls to SLF4J and Logback to control which messages appear and keep a rotating log on disk.

The configuration examples use SLF4J 2.x and Logback 1.5.12.

Why replace scattered console prints

A console print is handy when I am checking one value. Across a desktop app, prints leave no distinction between a troubleshooting detail and an error the user might report. They also give little control over timestamps, thread names, or retention. Synchronized writes to the same stream can contend, and blocking output on the event dispatch thread can make the UI feel slow.

Replacing direct console output in the Swing project Figure 1. The original project used direct console output for diagnostics.

What SLF4J does and where Logback fits

SLF4J is the API application classes use. A backend such as Logback implements the logging behavior. Application code obtains a logger through LoggerFactory, while the backend decides which events to write, how to format them, and which destinations receive them.

SLF4J 1.7 looked for a static binding through StaticLoggerBinder. SLF4J 2 uses ServiceLoader and an SLF4JServiceProvider descriptor. Keep one provider on the runtime classpath. A competing provider from a transitive dependency can cause a startup warning and choose a backend you did not intend to configure.

flowchart TD
    APP["Swing application"] --> API["SLF4J API"]
    API -->|"ServiceLoader provider"| LB["Logback Classic"]
    API -.-> OTHER["Alternative logging provider"]
    LB --> CONSOLE["Color console appender"]
    LB --> FILE["Rolling file appender"]
LevelWhat I use it for
TRACEA narrowly scoped investigation of detailed execution
DEBUGDiagnostics useful while debugging
INFOMajor normal events, such as startup or a completed operation
WARNA recovery or condition worth investigating
ERRORA failure that needs attention

Adding a dependency and logging from the UI

Use the dependency block appropriate for the project’s build tool. A library can depend on the SLF4J API alone. This application also needs a provider to write logs.

1
2
3
4
5
6
<!-- pom.xml -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.5.12</version>
</dependency>
1
2
3
4
// build.gradle.kts
dependencies {
    implementation("ch.qos.logback:logback-classic:1.5.12")
}

The Swing frame uses a class-named logger and supplies values to placeholders. A second example uses the SLF4J fluent API to attach structured key-value data. If Lombok already provides @Slf4j, the generated logger can use the same SLF4J methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// src/main/java/com/example/swing/MainFrame.java
package com.example.swing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainFrame {

    private static final Logger log = LoggerFactory.getLogger(MainFrame.class);

    public void loadUserProfile(String userId) {
        log.info("Loading the user profile. userId={}", userId);
        log.debug("Running on the event dispatch thread: isEDT={}", javax.swing.SwingUtilities.isEventDispatchThread());
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/main/java/com/example/swing/OrderPanel.java
package com.example.swing;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OrderPanel {

    public void submitOrder(String orderId, int amount) {
        // SLF4J 2.x fluent API supports structured arguments and lazy evaluation.
        log.atInfo()
            .addKeyValue("orderId", orderId)
            .addKeyValue("amount", amount)
            .log("Order request sent.");
    }
}

A console record includes the time, thread, logger, and level so I can see whether activity ran on the main thread or a worker.

1
03:01:10.885 [main] INFO  com.example.swing.MainFrame - Loading the user profile. userId=cmsong111

Configuring the console and rotating files

The XML file supplies separate console and rolling file appenders. Set the root logger to INFO and turn on DEBUG for the project’s package when it helps. The file policy rolls on both date and size, compresses archives, and applies a total size cap. That makes retention independent of the user’s habit of clearing logs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!-- src/main/resources/logback.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="LOG_DIR" value="./logs" />
    <property name="CONSOLE_PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) [%thread] %cyan(%logger{20}) - %msg%n" />
    <property name="FILE_PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n" />

    <!-- Color console appender for development -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${CONSOLE_PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- Date- and size-based rolling file appender -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/app.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_DIR}/app.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <maxFileSize>20MB</maxFileSize>
            <maxHistory>14</maxHistory>
            <totalSizeCap>500MB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${FILE_PATTERN}</pattern>
        </encoder>
    </appender>

    <!-- Enable DEBUG for the application package and leave other loggers at INFO -->
    <logger name="com.example.swing" level="DEBUG" />

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

Color-coded console level output Figure 2. The console formatter makes different log levels easier to distinguish.

Checking the setup

Use placeholders for scalar values and a supplier for expensive work, such as serializing a large object solely for a debug log. A Java expression passed as an ordinary method argument still runs even if the level is disabled. Keep verbose settings scoped so an HTTP dependency cannot fill the disk while tracing one UI workflow.

Start the desktop client, perform an operation handled by a worker, and find its output in both the console and the file. Check that package-level debug output can be enabled without turning it on for every dependency. If there is a provider warning, use the Gradle or Maven dependency tree to identify the extra provider and exclude it at the dependency that pulls it in.

This post is licensed under CC BY 4.0 by the author.