SLF4J (Simple Logging Facade for Java) is a logging abstraction that lets application code call a single, consistent logging API while the actual implementation—Logback, Log4j2, or java.util.logging—is plugged in at deployment time.
Key Points: • Code depends only on the org.slf4j.Logger interface, decoupling it from any specific logging framework. • The concrete implementation is chosen by which binding JAR is on the classpath, without changing application code. • Spring Boot uses SLF4J with Logback as the default underlying implementation. • It supports parameterized logging (e.g., log.info("User {} logged in", username)), avoiding costly string concatenation when the log level is disabled. • Switching logging frameworks later—say from Logback to Log4j2—requires only a dependency swap, not code changes.
Example: A library author codes against SLF4J's Logger interface so that any application using the library can route its logs through whichever framework—Logback, Log4j2—that application has already chosen.
Code Example:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public void placeOrder(String orderId) {
log.info("Order {} placed successfully", orderId);
}
}Interview Tip: A concise interview answer is:
"SLF4J is a logging facade—code logs against its Logger interface, and the actual framework doing the work, like Logback or Log4j2, is swapped in at deployment via the classpath binding. Spring Boot defaults to SLF4J with Logback, and it's the standard choice because it decouples application code from any specific logging implementation."