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.
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);Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Interview Crash Guide
Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
