Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Language Features by Version

Logging in Java

Reference for Java logging: System.Logger, java.util.logging levels, handlers and formatters, parameterized messages, and how SLF4J, Log4j 2 and Logback fit in.

Logging records what a program is doing so you can understand it later, in production or in a failing test, without a debugger. A good log line has a level (how serious), a source (which logger), a message and optionally an exception with its stack trace. Handlers decide where lines go (console, file, network) and formatters decide how they look.

The JDK contains two logging APIs. java.util.logging (JUL, since Java 1.4) is the full implementation with levels, handlers and formatters. System.Logger (Java 9) is a small facade in java.base for JDK code and libraries: it sends messages to whatever logging system is installed, and by default that is JUL. Most applications additionally use a third-party facade, usually SLF4J, with a backend such as Logback or Log4j 2.

Java
System.Logger log = System.getLogger("com.shop.orders");
log.log(System.Logger.Level.INFO, "Order {0} shipped to {1}", 42, "Lyon");

System.Logger

Member Description
System.getLogger(String name) Returns the logger for a name; the name is usually the class's fully qualified name
log(Level, String msg) Logs a message
log(Level, String format, Object... params) Logs a message with , placeholders (MessageFormat style)
log(Level, String msg, Throwable t) Logs a message with an exception
log(Level, Supplier<String> msg) Builds the message lazily, only if the level is enabled
isLoggable(Level) Tests whether a level would be logged

System.Logger.Level has ALL, TRACE, DEBUG, INFO, WARNING, ERROR and OFF.

java.util.logging levels

JUL Level Value System.Logger equivalent
SEVERE 1000 ERROR
WARNING 900 WARNING
INFO 800 INFO
CONFIG 700 none (between INFO and DEBUG)
FINE 500 DEBUG
FINER 400 TRACE
FINEST 300 none (below TRACE)

The default root level is INFO, so FINE and below are dropped unless you change the logger and the handler: both check the level.

Try it

Java java.util.logging with a custom handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java System.Logger routes to the installed backend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Third-party logging

Most real applications use SLF4J (Simple Logging Facade for Java) in code and pick the backend by adding a dependency. Read-only example:

Java
// Read-only: needs org.slf4j:slf4j-api plus a backend such as Logback on the class path
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

    void ship(int id, String city) {
        log.info("Order {} shipped to {}", id, city);        // {} placeholders, no string concatenation
        log.debug("Details: {}", expensive());               // arguments are only formatted when enabled
        try {
            charge(id);
        } catch (Exception e) {
            log.error("Charging order {} failed", id, e);    // the last argument may be the exception
        }
    }
}
Library Role
SLF4J Facade API; the usual choice in application and library code
Logback Native SLF4J implementation (default in Spring Boot)
Log4j 2 Fast, flexible backend with async loggers and many appenders
System.Logger JDK facade; Log4j 2 and Logback can route it through bridges
java.util.logging JDK backend; bridge to SLF4J with jul-to-slf4j

Usage notes

  • Choose levels deliberately. ERROR means a human should look at it; WARN is recoverable but suspicious; INFO records important lifecycle events; DEBUG and TRACE are for diagnosis and normally disabled in production.
  • Pass the exception as the last argument, not e.getMessage() concatenated into the text, so the stack trace is kept.
  • Do not build messages eagerly. "x=" + expensive() is evaluated even when the level is off. Use placeholders or a Supplier.
  • Never log secrets or personal data: passwords, tokens, card numbers. Mask or omit them.
  • Do not use System.out.println or printStackTrace() for diagnostics in servers. They have no levels, no timestamps, no routing and are hard to filter.
  • Log once. Catching, logging and rethrowing at every layer fills the log with duplicates; log where you handle the error.
  • Handler level and logger level both apply. In JUL, setting a logger to FINE does nothing visible while the console handler still has level INFO.
  • Configuration. JUL reads a file named by -Djava.util.logging.config.file=...; Logback reads logback.xml; Log4j 2 reads log4j2.xml.
  • Structured logging (JSON lines with key-value fields) makes logs searchable in tools like Elasticsearch or Loki; both Logback and Log4j 2 can produce it.