Skip to content
Tutorials Center
My learning

Topics

Lesson 163 of 201 ยท JVM and Advanced Topics

Logging

Learn Java logging - why println isn't enough, java.util.logging loggers, levels, handlers, formatters and config files, System.Logger and an SLF4J overview.

When you're learning, System.out.println is how you find out what your program is doing. In a real application that runs for weeks on a server, that habit breaks down. You can't delete the debug lines without editing code, you can't turn them back on when a bug appears at 3 a.m., and every line lacks the basics: when it happened, how serious it is and which part of the program wrote it.

Logging solves this. Instead of printing, your code sends messages to a logger with a level such as INFO or WARNING. Configuration, not code, then decides which messages are kept, how they look and where they go: the console, a file, or a log server. This lesson teaches the logging API built into the JDK, java.util.logging, which you can run right here: loggers, levels, the logger hierarchy, handlers, formatters, configuration files and logging exceptions properly. It ends with System.Logger and a first look at SLF4J and Logback, the tools most companies use, which the Advanced Java lesson Logging with SLF4J and Logback covers in depth.

Why not println?

Compare what each approach gives you:

Need println A logger
Timestamp, severity, source write it yourself on every line added automatically
Turn detail on/off edit and redeploy code change one config line
Different detail per package impossible com.shop.db.level = FINE
Write to a file, rotate old files write your own code a handler does it
Cost when disabled the string is still built and printed almost free

println is still fine for small command-line programs whose job is to print output. Logging is for diagnostic information about a running program.

Your first logger

java.util.logging (often called JUL) has been part of the JDK since Java 1.4, so it needs no dependency. You get a logger by name, conventionally the name of the class that uses it, and call a method named after the level:

Java A first logger and its levels

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.

Look closely at the output:

  • Each log message takes two lines: a timestamp plus the class and method that logged it, then LEVEL: message. That's the default SimpleFormatter.
  • Log messages go to standard error, while the IO.println lines go to standard output. That's why they may appear in a different order or color than you expect.
  • The config and fine messages are missing. By default only INFO and above are kept.

The seven levels

JUL has seven levels, from most to least severe, plus two special values:

Level Use it for
SEVERE a failure: something the program was supposed to do didn't happen
WARNING something unexpected that the program handled, but someone should look at
INFO important normal events: startup, shutdown, an order placed
CONFIG configuration details printed at startup
FINE debugging detail for developers
FINER, FINEST very detailed tracing (method entry and exit, loop steps)
OFF / ALL thresholds only: disable everything or enable everything

A logger keeps a message when the message's level is at or above the logger's threshold. Levels are ordered, so setting a threshold of WARNING keeps WARNING and SEVERE and drops the rest.

Loggers, handlers and formatters

Logging has three moving parts, and the same design appears in every Java logging library:

  1. A Logger is the object your code calls. It has a name and a level threshold.
  2. A Handler receives the messages that pass and sends them somewhere: ConsoleHandler (standard error), FileHandler, StreamHandler, SocketHandler. A handler has its own level, too.
  3. A Formatter turns a message (a LogRecord) into text: SimpleFormatter or XMLFormatter, or your own.

Logger names form a hierarchy at the dots, like packages. com.shop.payments is a child of com.shop, which is a child of com, whose parent is the root logger (named ""). Two rules follow from that:

  • A logger without its own level inherits the nearest ancestor's level.
  • A message that a logger accepts is also passed up to the handlers of every ancestor. The default ConsoleHandler is attached only to the root logger, which is why all loggers print to the console.

The usual way to configure all this is a logging.properties file, passed to the JVM with -Djava.util.logging.config.file=logging.properties. The sandbox can't pass JVM options, but LogManager.readConfiguration accepts the same file content from any input stream, so this example loads it from a text block:

Java Configuring logging with a properties file

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.

The SimpleFormatter.format property is a format string with numbered arguments: %1$ is the time, %2$ the source (class and method), %3$ the logger name, %4$ the level, %5$ the message and %6$ the exception's stack trace (empty when there's none). %1$tT prints the time as HH:MM:SS.

Notice getLevel() returns null for orders: it has no level of its own and inherits one. This also explains the most common JUL surprise. A message must pass two filters: the logger's level and the handler's level. The default ConsoleHandler accepts only INFO and above, so setting a logger to FINE in code shows nothing extra until you also lower the handler's level. That's why the config above sets ConsoleHandler.level = ALL and controls detail through logger levels only.

System.setErr(System.out) is a demo trick. ConsoleHandler writes to System.err, and our output panel shows standard output and standard error separately. Redirecting System.err before the handler is created keeps every line in order. Real applications leave both streams alone.

Writing logs to files

Servers usually log to files, and those files must not grow forever. FileHandler writes to a file and can rotate: when a file reaches a size limit, it starts a new one and keeps a fixed number of old files. The file name pattern uses %g for the generation number (0 is the newest), %u for a unique number when two programs share a name, and %t for the system temp folder.

Java FileHandler with size-based rotation

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.

Only the last few orders survive: older files were deleted once there were three. Real configurations use limits of tens of megabytes. The handler also creates a .lck lock file next to the log so that two programs don't write the same file. setUseParentHandlers(false) stops messages from traveling up to the root logger's console handler; without it, every line would also appear on the console.

You can write your own Formatter (as above) or Handler by extending the abstract classes. For JSON output, alerting or log servers, though, teams usually switch to a full logging framework (see the end of this lesson).

Logging exceptions and expensive messages

Two habits separate useful logs from useless ones.

Pass the exception itself, not just its message. log.log(level, message, throwable) records the full stack trace, including any "Caused by" chain. Logging only e.getMessage() loses the stack trace, and for many exceptions (like a NullPointerException thrown explicitly without text) the message is simply null.

Don't build messages that will be thrown away. In log.fine("Cart: " + cart.describe()), Java builds the string before calling fine, even if FINE is disabled. The logger methods also accept a Supplier<String>, which is only called when the message will really be logged.

Java Logging exceptions and lazy messages

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.

describeCart() ran once, for the concatenated version, even though nothing was logged. For a cheap message that doesn't matter; for a message that serializes a large object on every request, it does. Prefer the supplier form (or an isLoggable guard) whenever building the message costs real work.

A few more rules worth following from day one:

  • Log or rethrow, not both. If you catch an exception, log it, and rethrow it, the next layer usually logs it again, and one failure shows up as three stack traces. Handle it in one place (see Exception Handling Best Practices).
  • Add context. "Payment failed" is useless; "Payment failed for order 1001, card gateway timeout after 5 s" is actionable.
  • Never log secrets. Passwords, full card numbers, access tokens and session ids must not appear in logs. Mask them (****4242).
  • Choose levels honestly. If WARNING fires every minute during normal operation, people stop reading warnings.

System.Logger: the JDK's logging facade

Since Java 9, the JDK also offers System.Logger, a small interface for code that wants to log without choosing a framework. By default its messages are handled by java.util.logging, but if the application uses SLF4J or Log4j 2 with the right adapter on the classpath, the same calls go there instead. It uses its own level names:

Java
System.Logger log = System.getLogger("com.shop.Inventory");

log.log(System.Logger.Level.INFO, "Inventory service started");
log.log(System.Logger.Level.WARNING, "Low stock for {0}: {1} left", "SKU-881", 4);
log.log(System.Logger.Level.DEBUG, () -> "Expensive detail: " + buildReport());
log.log(System.Logger.Level.ERROR, "Reservation failed", exception);
System.Logger java.util.logging SLF4J
ERROR SEVERE error
WARNING WARNING warn
INFO INFO info
DEBUG FINE debug
TRACE FINER trace

SLF4J and Logback: what professionals use

Most production Java code doesn't call JUL directly. It logs through SLF4J (Simple Logging Facade for Java), an API with a separate implementation behind it, most often Logback (Spring Boot's default) or Log4j 2. Your code depends only on the facade, and the implementation is chosen when the application is assembled:

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

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

    void place(Order order) {
        log.info("Placing order {} for {}", order.id(), order.customerId());   // {} placeholders, lazy
        try {
            // ...
        } catch (PaymentException e) {
            log.error("Payment failed for order {}", order.id(), e);           // exception last
        }
    }
}

The {} placeholders are filled in only if the level is enabled, so SLF4J code rarely needs suppliers or guards. Logback is configured in src/main/resources/logback.xml:

XML
<configuration>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <logger name="com.shop.payments" level="DEBUG"/>

  <root level="INFO">
    <appender-ref ref="CONSOLE"/>
  </root>
</configuration>

The ideas are the ones you just learned: named loggers in a hierarchy, level thresholds, appenders (handlers) and encoders (formatters). SLF4J isn't on our sandbox's classpath, so these snippets are read-only. Dependencies, configuration, the MDC for request ids and JSON logs are covered in Logging with SLF4J and Logback; adding the dependency itself is a build tool job.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A logger has no level of its own, its parent com.shop is set to WARNING, and the root is INFO. Which of these messages is logged?

    The logger inherits the nearest ancestor's level, which is WARNING from com.shop. Only WARNING and SEVERE pass.
  2. 2. You call Logger.getLogger("com.shop").setLevel(Level.FINE) but fine messages still don't appear on the console. Why?

    A message must pass both the logger's level and the handler's level. Lower the ConsoleHandler's level (for example to ALL) as well.
  3. 3. With FINE disabled, how many times is report() called? log.fine("A " + report()); log.fine(() -> "B " + report());

    The concatenation is evaluated before fine is called, so report() runs once for the first line. The supplier in the second line is never called because the message is discarded.
  4. 4. What is the best way to log a caught exception?

    Passing the throwable records the full stack trace, including causes, through the configured handlers. getMessage() and toString() lose the trace, and printStackTrace bypasses logging entirely.

Summary

  • Use a logger instead of println for diagnostic output: levels, timestamps, sources, destinations and per-package detail come from configuration, not code.
  • java.util.logging is built in: Logger.getLogger(name), levels SEVERE > WARNING > INFO > CONFIG > FINE > FINER > FINEST, default threshold INFO.
  • Loggers form a dot-separated hierarchy; they inherit levels and pass messages up to their ancestors' handlers. Handlers have their own levels, and formatters shape the text.
  • Configure JUL with a logging.properties file; FileHandler writes to files and rotates them by size.
  • Log exceptions with log.log(level, message, e), avoid building disabled messages (suppliers or isLoggable), add context, and never log secrets.
  • System.Logger is the JDK's facade; most companies use SLF4J with Logback or Log4j 2, covered in Logging with SLF4J and Logback.

Next: Java Performance Tips, where you'll learn to measure before you optimize and which habits really make Java code faster.