0Pricing
Java Academy · Lesson

SLF4J Facade and Loggers

Log at the right level.

What Is SLF4J?

SLF4J (Simple Logging Facade for Java) is an abstraction. You code against its API, and a backend like Logback or Log4j2 does the actual logging.

This lets libraries log without forcing a specific implementation on the application.

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

public class Main {
    private static final Logger log = LoggerFactory.getLogger(Main.class);
    public static void main(String[] args) {
        log.info("Application started");
    }
}

Getting a Logger

Create one logger per class with LoggerFactory.getLogger(MyClass.class).

By convention the field is private static final and named log or logger. The class becomes the logger's name, which appears in output.

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

public class OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);
    void placeOrder(String id) {
        log.info("Placing order {}", id);
    }
}

All lessons in this course

  1. Why Structured Logging
  2. SLF4J Facade and Loggers
  3. Parameterized Logging
  4. Configuring Logback
← Back to Java Academy