Java Logging Basics
Java logging means writing messages about what your program is doing to the console or a file, each with a time, a severity level and the class that wrote it. Unlike System.out.println, log messages can be switched on or off per level and per package, sent to several places at once and rotated automatically. When something breaks in production, the logs are often the only record of what happened.
This lesson covers the built-in java.util.logging package, the System.Logger API, and the most popular combination in real projects: SLF4J with Logback. It ends by adding request logging to the CourseServer app used in Java Deployment. Examples were run with JDK 21, SLF4J 2.0 and Logback 1.5.
Why Use Java Logging Instead of System.out
| Feature | System.out.println | A logging framework |
|---|---|---|
| Timestamp and class name | No | Added automatically |
| Severity levels | No | ERROR, WARN, INFO, DEBUG, ... |
| Turn detail on/off without code changes | No | Yes, in a config file |
| Different detail per package | No | Yes |
| Write to console and file | No | Yes |
| Rotate and delete old log files | No | Yes |
| Print exception stack traces cleanly | Manual | One argument |
Log Levels Compared
| Meaning | java.util.logging | System.Logger | SLF4J / Logback |
|---|---|---|---|
| Something failed | SEVERE | ERROR | ERROR |
| Unexpected but handled | WARNING | WARNING | WARN |
| Normal milestones | INFO | INFO | INFO |
| Configuration details | CONFIG | — | — |
| Developer detail | FINE | DEBUG | DEBUG |
| Very detailed tracing | FINER, FINEST | TRACE | TRACE |
How it works:
- Each logger has a threshold level. Messages below it are dropped cheaply. With the level set to
INFO,DEBUGmessages cost almost nothing. - Production usually runs at
INFO. You switch one package toDEBUGwhile investigating a problem, then switch it back.
Java Logging With java.util.logging
java.util.logging (often called JUL) is built into the JDK, so it needs no dependencies.
import java.util.logging.Level;
import java.util.logging.Logger;
public class JulBasics {
// one logger per class, named after the class
private static final Logger LOGGER = Logger.getLogger(JulBasics.class.getName());
public static void main(String[] args) {
LOGGER.severe("Database is unreachable");
LOGGER.warning("Disk usage is at 91%");
LOGGER.info("Server starting on port 8080");
LOGGER.fine("Loaded 42 courses from cache"); // hidden by default
// parameters use {0}, {1} ... placeholders
LOGGER.log(Level.INFO, "User {0} enrolled in {1}", new Object[] {"asha", "Java Basics"});
try {
Integer.parseInt("forty-two");
} catch (NumberFormatException e) {
// pass the exception as the last argument to log its stack trace
LOGGER.log(Level.WARNING, "Invalid course count in request", e);
}
}
}
Nov 18, 2026 10:15:02 AM JulBasics main
SEVERE: Database is unreachable
Nov 18, 2026 10:15:02 AM JulBasics main
WARNING: Disk usage is at 91%
Nov 18, 2026 10:15:02 AM JulBasics main
INFO: Server starting on port 8080
Nov 18, 2026 10:15:02 AM JulBasics main
INFO: User asha enrolled in Java Basics
Nov 18, 2026 10:15:02 AM JulBasics main
WARNING: Invalid course count in request
java.lang.NumberFormatException: For input string: "forty-two"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:778)
at JulBasics.main(JulBasics.java:18)
How it works:
Logger.getLogger(JulBasics.class.getName())names the logger after the class. Logger names form a tree by package, which is how you configure whole packages at once.- The default configuration logs
INFOand above to stderr, so thefine()message is not printed. - The default format uses two lines per message. The next section changes that to one line.
- Passing the exception as the last argument prints the full stack trace. Never log only
e.getMessage(); you lose the line number where the error happened.
Configure java.util.logging With logging.properties
A properties file controls levels, output targets (handlers) and the message format.
# logging.properties
# send log records to the console and to a file
handlers=java.util.logging.ConsoleHandler, java.util.logging.FileHandler
# root level: what is logged at all
.level=INFO
# more detail for our own package only
com.gocourse.level=FINE
java.util.logging.ConsoleHandler.level=FINE
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
# logs/app0.log, logs/app1.log ... max 1 MB each, keep 3 files
java.util.logging.FileHandler.pattern=logs/app%g.log
java.util.logging.FileHandler.limit=1000000
java.util.logging.FileHandler.count=3
java.util.logging.FileHandler.append=true
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
# one line per record: date time level logger - message [exception]
java.util.logging.SimpleFormatter.format=%1$tF %1$tT %4$-7s %3$s - %5$s%6$s%n
package com.gocourse.app;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EnrollmentService {
private static final Logger LOGGER = Logger.getLogger(EnrollmentService.class.getName());
public static void main(String[] args) {
LOGGER.info("Enrollment service started");
LOGGER.fine("Cache warmed with 42 courses"); // visible: com.gocourse is FINE
LOGGER.finer("Cache key list: [java, go, html]"); // still hidden
LOGGER.log(Level.WARNING, "Course {0} is full", "java-basics");
Logger.getLogger("org.example.Library").fine("library detail"); // hidden: root is INFO
}
}
mkdir -p logs
java -Djava.util.logging.config.file=logging.properties -cp out com.gocourse.app.EnrollmentService
cat logs/app0.log
2026-11-18 10:15:30 INFO com.gocourse.app.EnrollmentService - Enrollment service started
2026-11-18 10:15:30 FINE com.gocourse.app.EnrollmentService - Cache warmed with 42 courses
2026-11-18 10:15:30 WARNING com.gocourse.app.EnrollmentService - Course java-basics is full
2026-11-18 10:15:30 INFO com.gocourse.app.EnrollmentService - Enrollment service started
2026-11-18 10:15:30 FINE com.gocourse.app.EnrollmentService - Cache warmed with 42 courses
2026-11-18 10:15:30 WARNING com.gocourse.app.EnrollmentService - Course java-basics is full
SimpleFormatter Placeholders
| Placeholder | Value |
|---|---|
%1$tF %1$tT | Date and time (2026-11-18 10:15:30) |
%2$s | Source class and method |
%3$s | Logger name |
%4$s / %4$-7s | Level (padded to 7 characters) |
%5$s | The message |
%6$s | The exception and stack trace, if any |
%n | Line break |
How it works:
- The first three lines come from the console handler, the last three from
cat logs/app0.log. Both handlers received the same records. - Two settings must allow a message: the logger level (
com.gocourse.level=FINE) and the handler level (ConsoleHandler.level=FINE). The console handler's default level isINFO, which is why it is raised here. - The
org.example.Librarymessage is dropped because onlycom.gocoursewas set toFINE. This keeps third-party libraries quiet. FileHandlerrotates by size: whenapp0.logreaches the limit, it is renamed toapp1.logand a newapp0.logstarts.%gis the generation number.
The System.Logger API
Since Java 9, System.Logger is a small logging interface in java.lang. Library authors like it because it does not tie users to one framework: by default it writes through java.util.logging, but it can be routed to SLF4J or Log4j.
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
public class SystemLoggerDemo {
private static final Logger LOGGER = System.getLogger(SystemLoggerDemo.class.getName());
public static void main(String[] args) {
LOGGER.log(Level.INFO, "Payment service ready");
LOGGER.log(Level.WARNING, "Retrying payment {0} (attempt {1})", "PAY-1007", 2);
// the message is built only if DEBUG is enabled
LOGGER.log(Level.DEBUG, () -> "Gateway response: " + slowToString());
}
static String slowToString() {
System.out.println("(slowToString was called)");
return "{...}";
}
}
java -Djava.util.logging.SimpleFormatter.format='%4$s: %5$s%n' -cp out SystemLoggerDemo
INFO: Payment service ready
WARNING: Retrying payment PAY-1007 (attempt 2)
How it works:
- The levels are named
DEBUGandWARNINGhere, but they map to JUL'sFINEandWARNINGbehind the scenes. - The
DEBUGmessage uses a supplier (() -> ...). BecauseDEBUGis disabled, the lambda never runs, and(slowToString was called)is never printed. Use suppliers when building the message is expensive. -Djava.util.logging.SimpleFormatter.formatchanges the format without a properties file.
SLF4J and Logback: The Standard Java Logging Stack
Most Java projects, including every Spring Boot app, use SLF4J as the API in their code and Logback as the implementation that actually writes the logs. Code depends only on SLF4J, so the backend can be swapped without code changes.
<!-- pom.xml -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.17</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.21</version>
</dependency>
// build.gradle.kts
dependencies {
implementation("org.slf4j:slf4j-api:2.0.17")
runtimeOnly("ch.qos.logback:logback-classic:1.5.21")
}
package com.gocourse.shop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public void placeOrder(long orderId, String customer, double total) {
log.info("Order {} placed by {} for {}", orderId, customer, total);
log.debug("Order {} has {} items", orderId, 3);
try {
if (total > 2000) throw new IllegalStateException("card limit exceeded");
} catch (IllegalStateException e) {
log.error("Payment failed for order {}", orderId, e); // exception last
}
}
public static void main(String[] args) {
new OrderService().placeOrder(1001, "asha", 2499.0);
}
}
10:16:05.211 [main] INFO com.gocourse.shop.OrderService -- Order 1001 placed by asha for 2499.0
10:16:05.214 [main] DEBUG com.gocourse.shop.OrderService -- Order 1001 has 3 items
10:16:05.215 [main] ERROR com.gocourse.shop.OrderService -- Payment failed for order 1001
java.lang.IllegalStateException: card limit exceeded
at com.gocourse.shop.OrderService.placeOrder(OrderService.java:13)
at com.gocourse.shop.OrderService.main(OrderService.java:20)
How it works:
{}placeholders are filled in only if the level is enabled, solog.debug("... {}", value)is cheap whenDEBUGis off. Never build messages with+in log calls.- If the last argument is an exception and has no matching
{}, SLF4J treats it as the exception and prints its stack trace. - Without a config file, Logback logs everything at
DEBUGand above to the console. That is why thedebugline appears. Alogback.xmlfile sets proper levels. - If you see
SLF4J(W): No SLF4J providers were found, the API is on the classpath but Logback is not. Addlogback-classic.
Configure Logback With logback.xml
Logback reads logback.xml from the classpath (src/main/resources). This one logs to the console and to a daily, size-limited rolling file.
<!-- src/main/resources/logback.xml -->
<configuration>
<!-- read from env vars, with defaults after :- -->
<property name="LOG_DIR" value="${LOG_DIR:-logs}"/>
<property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n"/>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_DIR}/app.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_DIR}/app-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
<maxFileSize>10MB</maxFileSize>
<maxHistory>14</maxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<!-- our code: DEBUG; noisy library: WARN only -->
<logger name="com.gocourse" level="DEBUG"/>
<logger name="com.zaxxer.hikari" level="WARN"/>
<root level="${LOG_LEVEL:-INFO}">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
java -cp "target/classes:target/lib/*" com.gocourse.shop.OrderService 2>&1 | head -n 2
ls logs
2026-11-18 10:17:41.902 INFO [main] com.gocourse.shop.OrderService - Order 1001 placed by asha for 2499.0
2026-11-18 10:17:41.905 DEBUG [main] com.gocourse.shop.OrderService - Order 1001 has 3 items
app.log
Common Logback Pattern Words
| Pattern | Output |
|---|---|
%d{yyyy-MM-dd HH:mm:ss.SSS} | Date and time with milliseconds |
%-5level | Level, padded to 5 characters |
%thread | Thread name, e.g. main or pool-1-thread-3 |
%logger{36} | Logger name, shortened to about 36 characters |
%msg | The message with {} filled in |
%X{requestId} | A value from the MDC (next section) |
%n | Line break |
How it works:
SizeAndTimeBasedRollingPolicystarts a new file every day and whenever the current one reaches 10 MB. Old files are gzipped, kept for 14 days, and deleted once all logs together exceed 1 GB, so the disk never fills up.${LOG_LEVEL:-INFO}reads an environment variable with a default. SettingLOG_LEVEL=DEBUGin the systemdapp.envor Dockerenv_filechanges the level without a rebuild, using the same approach as Java Environment Variables.- In containers, use only the
CONSOLEappender. Docker collects stdout, as shown in Dockerize a Java Application, and log files inside a container are lost when it is replaced.
Add Context to Java Logs With MDC
When many requests run at once, their log lines mix together. The MDC (Mapped Diagnostic Context) attaches values such as a request ID to every log line written by the current thread.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.util.UUID;
public class CheckoutHandler {
private static final Logger log = LoggerFactory.getLogger(CheckoutHandler.class);
void handle(String customer) {
MDC.put("requestId", UUID.randomUUID().toString().substring(0, 8));
MDC.put("user", customer);
try {
log.info("Checkout started");
log.info("Charged card");
} finally {
MDC.clear(); // threads are reused; never leak context into the next request
}
}
}
<pattern>%d{HH:mm:ss.SSS} %-5level [%X{requestId}] [%X{user}] %logger{20} - %msg%n</pattern>
10:18:12.330 INFO [3f9c1a7e] [asha] CheckoutHandler - Checkout started
10:18:12.331 INFO [b81d04c2] [ravi] CheckoutHandler - Checkout started
10:18:12.335 INFO [3f9c1a7e] [asha] CheckoutHandler - Charged card
10:18:12.337 INFO [b81d04c2] [ravi] CheckoutHandler - Charged card
How it works:
MDC.putstores a value for the current thread only.%X{requestId}prints it in every line, even from classes that know nothing about the request.- Searching the log for
3f9c1a7enow shows the complete story of one request. finally { MDC.clear(); }is essential with thread pools: a reused thread would otherwise carry the previous request's ID.
Avoid Expensive Log Messages
Even with placeholders, the arguments are evaluated before the call. For costly values, check the level first or use SLF4J 2's fluent API with a supplier.
// option 1: guard
if (log.isDebugEnabled()) {
log.debug("Cart contents: {}", cart.describeEveryItem());
}
// option 2: fluent API, the supplier runs only when DEBUG is on
log.atDebug()
.setMessage("Cart contents: {}")
.addArgument(() -> cart.describeEveryItem())
.log();
How it works:
- With the level at
INFO, neither version callsdescribeEveryItem(). A plainlog.debug("...", cart.describeEveryItem())would call it every time and throw the result away. - Use this only for genuinely expensive values. For simple variables, normal
{}placeholders are already cheap.
Note: Never log passwords, tokens, full card numbers or personal data. Logs are copied to many places and kept for a long time. Mask secrets the same way the
AppConfigsummary did in the previous lesson.
Real-World Example: Request Logging in CourseServer With SLF4J
This version of the CourseServer logs startup, every HTTP request with a request ID, its status and duration, and slow requests as warnings. The log level comes from LOG_LEVEL.
package com.gocourse.app;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.Executors;
public class CourseServer {
private static final Logger log = LoggerFactory.getLogger(CourseServer.class);
private static final Logger access = LoggerFactory.getLogger("access");
private static final long SLOW_MS = 500;
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(System.getenv().getOrDefault("APP_PORT", "8080"));
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.setExecutor(Executors.newFixedThreadPool(4));
server.createContext("/api/courses", logged(exchange -> send(exchange, 200, "[\"java\",\"go\",\"html\"]")));
server.createContext("/api/report", logged(exchange -> {
sleep(750); // simulate a slow database query
send(exchange, 200, "{\"students\":312}");
}));
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
log.info("Shutdown requested, stopping HTTP server");
server.stop(2);
}));
server.start();
log.info("CourseServer started on port {} (java {})", port, Runtime.version().feature());
}
/** Wraps a handler: sets the MDC, measures time and logs one access line per request. */
static HttpHandler logged(HttpHandler handler) {
return exchange -> {
long start = System.nanoTime();
String requestId = exchange.getRequestHeaders().getFirst("X-Request-Id");
MDC.put("requestId", requestId != null ? requestId : UUID.randomUUID().toString().substring(0, 8));
try {
log.debug("Handling {} {}", exchange.getRequestMethod(), exchange.getRequestURI());
handler.handle(exchange);
} catch (Exception e) {
log.error("Request failed: {} {}", exchange.getRequestMethod(), exchange.getRequestURI(), e);
send(exchange, 500, "{\"error\":\"internal\"}");
} finally {
long millis = (System.nanoTime() - start) / 1_000_000;
int status = exchange.getResponseCode();
if (millis > SLOW_MS) {
access.warn("{} {} -> {} in {} ms (slow)", exchange.getRequestMethod(), exchange.getRequestURI(), status, millis);
} else {
access.info("{} {} -> {} in {} ms", exchange.getRequestMethod(), exchange.getRequestURI(), status, millis);
}
MDC.clear();
}
};
}
static void send(HttpExchange exchange, int status, String json) throws IOException {
byte[] body = json.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(status, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
<!-- src/main/resources/logback.xml -->
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread] [%X{requestId:--}] %logger{20} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.gocourse" level="${LOG_LEVEL:-INFO}"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>
java -jar course-server.jar &
curl -s -o /dev/null http://localhost:8080/api/courses
curl -s -o /dev/null -H "X-Request-Id: support-42" http://localhost:8080/api/report
10:20:03.118 INFO [main] [-] c.g.app.CourseServer - CourseServer started on port 8080 (java 21)
10:20:09.402 INFO [pool-1-thread-1] [7d2e9b14] access - GET /api/courses -> 200 in 3 ms
10:20:15.877 WARN [pool-1-thread-2] [support-42] access - GET /api/report -> 200 in 752 ms (slow)
Restart with more detail for our own code only:
LOG_LEVEL=DEBUG java -jar course-server.jar &
curl -s -o /dev/null http://localhost:8080/api/courses
10:21:40.550 INFO [main] [-] c.g.app.CourseServer - CourseServer started on port 8080 (java 21)
10:21:44.019 DEBUG [pool-1-thread-1] [a03f6c55] c.g.app.CourseServer - Handling GET /api/courses
10:21:44.021 INFO [pool-1-thread-1] [a03f6c55] access - GET /api/courses -> 200 in 2 ms
How it works:
- One wrapper, every request.
logged()wraps each handler, so request IDs, timing and error handling are written once instead of in every endpoint. - Traceable requests. The request ID comes from an
X-Request-Idheader when a proxy or client sends one (support-42), or is generated.%X{requestId:--}prints-when no ID is set, as in the startup line. - Separate access logger. Request lines use a logger named
access, so you can send them to their own file or level without touching application logs. Slow requests are logged atWARN, making them easy to find withgrep WARN. - Errors with stack traces. Any exception in a handler is logged at
ERRORwith the full trace and turned into a500response, so one bad request never kills the server thread. - Level from the environment.
LOG_LEVEL=DEBUGswitches onHandling ...lines forcom.gocourseonly, while libraries stay atINFO. Under systemd these lines go tojournalctl, and in Docker todocker logs, with no code changes.