Sub topic 1
Why logging matters and what to log
Prerequisites
This chapter assumes you already know the following:
- Basic Java syntax, including classes, methods, and exceptions.
- How to run a simple Spring Boot application built with Maven or Gradle.
- How
application.propertiesorapplication.ymlworks. - The basic idea of Spring profiles, such as
devandprod.
You do not need any prior knowledge of SLF4J or Logback. Later chapters introduce them.
Why logging matters
A running application is hard to observe. You cannot attach a debugger to a production server, and you often cannot reproduce a customer's problem on your own machine. Logs are the record the application writes about itself while it runs. They are often the only evidence of what happened.
Logs serve four main purposes:
- Diagnosis. When a request fails, the log shows the exception, the input that caused it, and what the application did just before it failed.
- Auditing. Logs can record who did what and when, for example "user 42 changed the shipping address on order 9001".
- Monitoring. Teams count errors and measure slow operations in logs, and they set up alerts on those numbers.
- Understanding behavior. Logs show the path a request took through your services. This helps when you inherit code you did not write.
Logging has a cost. Every log call uses CPU time and I/O, and every line takes up disk space and, in a hosted system, money. Too little logging leaves you blind during an incident. Too much hides the useful lines in noise and slows the application. The goal of this tutorial is to help you find a sensible middle.
Logs compared with other tools
Logging is one of several ways to observe an application. It helps to know where it fits.
| Tool | Answers the question | Typical form |
|---|---|---|
| Logs | What happened, and in what order? | Text lines or JSON events with a timestamp |
| Metrics | How much, how often, how fast? | Numbers sampled over time |
| Traces | Where did one request spend its time across services? | A tree of timed spans |
| Debugger | What is the state of the program right now? | Interactive, local only |
Logs are the most detailed of the first three, but they are poor at answering "how many" questions across millions of events. Use metrics for counts and rates. Use logs for the story behind a single event.
What Spring Boot gives you
Spring Boot logs to the console out of the box. When you start any application, you see startup messages from Spring itself. You did not write any configuration for this. Boot chooses a logging library, sets a default format, and sets a default level.
The default configuration works for a first run. It is rarely right for production. You will want to control which messages appear, where they go, what they look like, and what information they carry. The rest of this tutorial covers each of those decisions in turn.
Each box in this diagram becomes a topic in a later chapter. The level check, the pattern, and the destinations are all configurable.
What to log
Deciding what to log is a design decision, like deciding what to name a method. A useful rule is to log events that someone will need to understand later, without having to read the code first.
Good candidates
- Application lifecycle events. Startup, shutdown, and important configuration choices, such as which profile is active. Spring Boot already logs some of these.
- Business events. An order was placed, a payment was refused, a user account was locked. Include the identifier of the thing involved.
- Boundaries with other systems. A call to a payment provider, a message sent to a queue, a database operation that failed. Failures at a boundary are common, and the log is where you find out which side was at fault.
- Errors and unexpected states. Every caught exception that you do not rethrow should be logged with its stack trace. Include the data that explains why it happened.
- Decisions that are not obvious. If code takes a fallback path, retries an operation, or skips a record, log it. Silent fallbacks are a common source of mysteries.
- Slow operations. Record the duration of calls that are expected to be quick but sometimes are not.
Poor candidates
- Every method entry and exit. This produces large volumes of low-value text. A debugger or a tracing tool does this job better.
- Inside tight loops. A log line that runs a million times per minute can slow the application and fill a disk.
- Sensitive data. Passwords, access tokens, full card numbers, national ID numbers, and session cookies must never appear in logs. Logs are often copied to other systems and read by more people than the database is.
- Whole request or response bodies by default. They are large and often contain personal data. Log selected fields instead.
- Messages that only repeat the code. A line like
"Entering method"tells the reader nothing.
Write for the reader
A log line is read later, by a person who is probably under pressure. That person may not be you. Write each message so that it makes sense alone.
Compare these two messages:
log.info("Done");
log.info("Order {} shipped to warehouse {} in {} ms", orderId, warehouseId, elapsedMs);The first message says nothing about what finished. The second names the event and carries the identifiers needed to find related lines. Searching for an order ID in the logs of a production system is a normal task, so make it possible.
A good message has these properties:
- It states what happened in plain words, in the past tense or as a clear state.
- It includes the identifiers needed to connect it to other events.
- It includes the values that explain the outcome, such as a count, a duration, or a status.
- It does not depend on the line before it for meaning.
What a log line contains
Spring Boot's default console format has several parts. A typical line looks like this:
2026-12-01T10:52:09.327Z INFO 4812 --- [main] com.example.orders.OrderService : Placing order A-1001 with 3 items| Part | Example | Meaning |
|---|---|---|
| Timestamp | `2026-12-01T10:52:09.327Z` | When the event happened |
| Level | `INFO` | How important the event is |
| Process ID | `4812` | The operating system process that wrote it |
| Thread name | `[main]` | The thread that ran the code |
| Logger name | `com.example.orders.OrderService` | The class or category that wrote it, usually shortened |
| Message | `Placing order A-1001 with 3 items` | The text you wrote |
The exact layout varies by Boot version, but the same information is present. The level and logger name matter most for configuration. The level controls whether the line is written. The logger name lets you control levels for one package without touching others.
A first look at a log statement
The following class logs a business event and an error. You do not need to understand every part yet. The next chapters explain the logger, the levels, and the placeholders in detail.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public void placeOrder(String orderId, int items) {
log.info("Placing order {} with {} items", orderId, items);
try {
process(orderId);
} catch (IllegalStateException ex) {
log.error("Order {} failed", orderId, ex);
}
}
private void process(String orderId) {
log.debug("Processing order {}", orderId);
}
}Three habits are visible here:
- The message names the event and includes the order ID.
- The error is logged once, where it is handled, with the exception passed as the last argument so the stack trace is kept.
- The detail about processing is at a lower level, so it can be hidden in production and shown when needed.
Common mistakes to avoid early
- Using
System.out.printlnfor diagnostics. It has no levels, no timestamps, no configuration, and no routing. A logging library gives you all four. - Logging an exception and rethrowing it. The same stack trace then appears at every layer that catches it. Log it where you handle it, not where you pass it on.
- Logging only the exception message.
log.error(ex.getMessage())drops the stack trace and the context. Pass the exception object itself. - Logging secrets by accident. Be careful when you log an entire object. Its
toString()method may include fields you did not intend to expose. - Treating logs as a database. Logs are for people and tools to read. Do not build application behavior that depends on parsing them.
Summary of the approach
The rest of the tutorial follows the path in the diagram. You will learn how Spring Boot assembles its logging stack, how levels work, and how to write statements properly. Then you will configure levels, outputs, and patterns, add request context, produce structured output, and change levels on a live system. The choices you make there are easier when you have decided first what is worth logging and who will read it.
Exercise
A teammate adds log.info("Request body: {}", requestBody) to a login endpoint, and also logs "Error" inside a catch block. Name two problems with these changes and say how you would fix each.
Show answer
First, the login request body probably contains a password, so logging it exposes sensitive data. Fix it by removing the line, or by logging only safe fields such as the username or a request ID. Second, the message "Error" says nothing about what failed, and it may not include the exception. Fix it by writing a message that names the event and its identifiers, and by passing the exception as the last argument, for example log.error("Login failed for user {}", username, ex).
Exercise
You need to know how many orders were placed per minute across ten service instances, and also why order A-1001 failed. Which tool fits each question best, logs or metrics?
Show answer
Use metrics for the orders-per-minute question, because metrics are numbers sampled over time and are cheap to aggregate across instances. Use logs for the A-1001 question, because logs record the detailed sequence of events and the exception for one specific order.