Mastering SLF4J: Best Practices for Effective Logging in Java

This guide explains how to use SLF4J with Logback, when and how to log at different levels, proper message formatting with placeholders, avoiding string concatenation, and provides practical code examples for ERROR, WARN, INFO, DEBUG, and TRACE logging in Java applications.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Mastering SLF4J: Best Practices for Effective Logging in Java

Using SLF4J

Adopt a facade logging framework to unify log handling across classes; Logback is recommended as the implementation.

When to Log

Log when debugging problems that cannot be resolved with a debugger.

Log at the start of each branch (if/else, switch) to identify the executed path.

Log the overall flow before committing code to ensure the process is traceable.

Basic Format

Use parameterized messages instead of string concatenation:

logger.debug("Processing trade with id:[{}] and symbol:[{}]", id, symbol);

Check the log level before logging debug messages:

if (logger.isDebugEnabled()) {
    logger.debug("Processing trade with id: " + id + " symbol: " + symbol);
}

Avoid string concatenation to prevent unnecessary object creation.

Incorrect example:

logger.debug("Processing trade with id: " + id + " symbol: " + symbol);

Using Parameter Placeholders

Write logs with placeholders for better readability and troubleshooting:

logger.debug("Processing trade with id:[{}] and symbol:[{}]", id, symbol);

Log Levels

ERROR

Log critical failures that affect program execution, such as configuration file loading failures or third‑party errors.

log.error("Error retrieving user [{}] information", userName, e);

Do not log errors when re‑throwing exceptions; let the final handler log them.

try {
    // ...
} catch (Exception ex) {
    logger.error("Error while reading information of user [%s]", userName, ex);
    throw new UserServiceException(errorMessage, ex);
}

WARN

Log situations that do not stop the current request but indicate potential issues, such as recoverable errors or near‑threshold conditions (e.g., cache pool reaching warning level).

INFO

Log normal system operation details, such as state changes in services, step‑by‑step progress, and external interface request/response parameters.

log.info("Starting query base");
log.info("Created user and bound mobile. userId=[{}], openId=[{}], mobile=[{}]", user.getId(), user.getOpenId(), mobile);

DEBUG

Log detailed information useful for debugging, including relevant parameters; disable in production or control via a switch.

TRACE

Use only for extremely fine‑grained tracing; generally avoid in business code.

Code Optimization Example

Improved logging statements with placeholders and clear messages:

logger.debug("Starting to get employee [{}] [{}] basic salary", employee, year);
logger.debug("Employee [{}] [{}] year [{}] month leave: annual=[{}], sick=[{}], no‑pay=[{}]", employee, year, month, annualLeaveDays, sickLeaveDays, noPayLeaveDays);
logger.debug("Calculated salary for employee [{}] [{}] month [{}] = [{}]", employee, year, month, actualSalary);
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javalogbackslf4j
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.