Reading production logs
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)An order failed in ShopLite production at 14:05 and you cannot attach a debugger. The logs are all you have, so every line must be easy to search and tied to its request.
Logs go to stdout; the platform collects them
Standard output (stdout) is the stream a program prints to by default. A containerised app logs to stdout instead of files, and Docker or the platform collects the stream, adds a timestamp and shows it in a log viewer.
Files inside a container disappear when it is replaced, so ShopLite logs to stdout and never to logs/app.log. On the VM you read the stream with docker compose logs.
# On the VM: the last 30 minutes of the API, following new linesdocker compose logs api --since 30m -f# Only the lines, without the "shoplite-api-1 | " prefix (handy for jq)docker compose logs --no-log-prefix api --since 30mNothing changes in your code: you know logger names, levels and SLF4J from Sections 15 and 18. What changes is where you read, the docker compose logs command on a VM or the platform's log page with its search box. Most platforms keep logs only from a few days to a month, so copy what you need for an incident report.
Structured JSON logs
A structured log is a log line written as a JSON object with named fields, such as level, time and requestId, instead of free text. A search tool can then ask for level ERROR and one requestId exactly.
Spring Boot 3.4 and later writes structured logs with one property, logging.structured.format.console. ShopLite's prod profile uses the ecs format.
Example 1 · application-prod.yml: one JSON object per log line
Runs in: the shoplite-api Spring Boot project, started with the prod profile
logging: structured: format: console: ecs # or logstash level: root: INFO com.shoplite: INFO{"@timestamp":"2026-10-16T08:35:02.118Z","log":{"level":"INFO","logger":"com.shoplite.order.OrderService"},"process":{"pid":1,"thread":{"name":"http-nio-8080-exec-4"}},"service":{"name":"shoplite-api"},"message":"Placing order for customer 1 with 2 items","requestId":"7f3a91c2","ecs":{"version":"8.11"}}
{"@timestamp":"2026-10-16T08:35:02.311Z","log":{"level":"ERROR","logger":"com.shoplite.common.GlobalExceptionHandler"},"process":{"pid":1,"thread":{"name":"http-nio-8080-exec-4"}},"service":{"name":"shoplite-api"},"message":"Unexpected error on POST /api/v1/me/orders","requestId":"7f3a91c2","error":{"type":"org.springframework.dao.InvalidDataAccessResourceUsageException","message":"could not execute statement [Unknown column 'gift_note' in 'field list']","stack_trace":"..."},"ecs":{"version":"8.11"}}What this code does
- Every line is a complete JSON object: the platform or
jqcan filter onlog.level,requestIdorerror.typewithout guessing at text. requestIdcomes from the MDC, so both lines of this request carry the same id. The exact set of fields differs a little between Boot versions and betweenecsandlogstash.
The format can be ecs (Elastic Common Schema), logstash or gelf. Each ECS line holds @timestamp (always UTC), the level and logger, the thread, the service name, the message and, for errors, the exception type, message and stack trace.
A JSON log writer and filter you can run
A request id is a short unique value given to each incoming request and written on every log line it causes. Filtering the logs by it shows the whole story of one request.
The program below writes one JSON object per line, with correct escaping of quotes in messages, then reads the lines back and keeps only those of one request.
Example 2 · Writing and filtering JSON log lines
import java.time.Instant;import java.util.ArrayList;import java.util.List;
public class JsonLogDemo { static final List<String> output = new ArrayList<>(); // stands in for stdout
static String escape(String s) { return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n"); }
static void log(Instant time, String level, String requestId, String message) { String line = "{\"@timestamp\":\"" + time + "\",\"level\":\"" + level + "\",\"requestId\":\"" + requestId + "\",\"message\":\"" + escape(message) + "\"}"; output.add(line); System.out.println(line); }
public static void main(String[] args) { Instant t = Instant.parse("2026-10-16T08:35:02Z"); log(t, "INFO", "7f3a91c2", "Placing order for customer 1 with 2 items"); log(t.plusMillis(40), "INFO", "b81e0d55", "Listed page 0 of products"); log(t.plusMillis(120), "WARN", "7f3a91c2", "Stock low for SKU \"ACC-AD141\": 3 left"); log(t.plusMillis(190), "ERROR", "7f3a91c2", "Order failed: Unknown column 'gift_note'");
System.out.println("--- only request 7f3a91c2 ---"); output.stream() .filter(line -> line.contains("\"requestId\":\"7f3a91c2\"")) .forEach(System.out::println); }}{"@timestamp":"2026-10-16T08:35:02Z","level":"INFO","requestId":"7f3a91c2","message":"Placing order for customer 1 with 2 items"}
{"@timestamp":"2026-10-16T08:35:02.040Z","level":"INFO","requestId":"b81e0d55","message":"Listed page 0 of products"}
{"@timestamp":"2026-10-16T08:35:02.120Z","level":"WARN","requestId":"7f3a91c2","message":"Stock low for SKU \"ACC-AD141\": 3 left"}
{"@timestamp":"2026-10-16T08:35:02.190Z","level":"ERROR","requestId":"7f3a91c2","message":"Order failed: Unknown column 'gift_note'"}
--- only request 7f3a91c2 ---
{"@timestamp":"2026-10-16T08:35:02Z","level":"INFO","requestId":"7f3a91c2","message":"Placing order for customer 1 with 2 items"}
{"@timestamp":"2026-10-16T08:35:02.120Z","level":"WARN","requestId":"7f3a91c2","message":"Stock low for SKU \"ACC-AD141\": 3 left"}
{"@timestamp":"2026-10-16T08:35:02.190Z","level":"ERROR","requestId":"7f3a91c2","message":"Order failed: Unknown column 'gift_note'"}What this code does
escapeturns"into\"(and newlines into\n), so a message with quotes still produces valid JSON; without it, the WARN line would break any JSON reader. The times are fixed so the output is the same on every run.- The filter matches the whole field
"requestId":"7f3a91c2", not just the id text, so it cannot match an id that merely contains the same characters. Three lines of one request appear in order; the other request's line is gone.
Filtering by a field is exact and fast; filtering by text is not. A search for 17 would also match orderId=170 and a time like 10:17.
Predict the output
Text search or field filter?
Read the log lines and pick the number of matches.
Round 1 of 2
A text search for 17 over these three lines. How many match?
Searching: time window, level and request id
MDC (Mapped Diagnostic Context) is a per-thread map in SLF4J whose entries are copied into every log line. ShopLite puts the requestId there, so all lines of one request carry the same id.
ShopLite adds a small request id filter that puts an id in the MDC for each request. The code below shows the filter, then the search that uses the id.
Example 3 · RequestIdFilter: one id per request, in the MDC and the response
Runs in: the shoplite-api Spring Boot project (src/main/java/com/shoplite/common/RequestIdFilter.java)
package com.shoplite.common;
import jakarta.servlet.FilterChain;import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.UUID;import org.slf4j.MDC;import org.springframework.core.Ordered;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;import org.springframework.web.filter.OncePerRequestFilter;
@Component@Order(Ordered.HIGHEST_PRECEDENCE)public class RequestIdFilter extends OncePerRequestFilter {
static final String HEADER = "X-Request-Id";
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String id = request.getHeader(HEADER); if (id == null || !id.matches("[A-Za-z0-9-]{1,64}")) { // never trust odd input in logs id = UUID.randomUUID().toString().substring(0, 8); } MDC.put("requestId", id); response.setHeader(HEADER, id); try { chain.doFilter(request, response); } finally { MDC.remove("requestId"); // threads are reused } }}$ curl -i -X POST https://api.shoplite.example/api/v1/me/orders -H "Authorization: Bearer $ASHA" \
-H "Content-Type: application/json" -d '{"addressId":1,"items":[{"productId":6,"quantity":2}]}'
HTTP/2 500
content-type: application/problem+json
x-request-id: 7f3a91c2
{"type":"https://shoplite.example/problems/internal-error","title":"Internal server error","status":500,"detail":"Something went wrong on our side. Please try again later.","instance":"/api/v1/me/orders"}What this code does
- The id goes into the MDC before the request runs, so every log line of this request, in any class, carries
requestId;finallyremoves it because Tomcat reuses the thread for the next request. - The response header gives the user (or the frontend) the same id. The error body stays generic, but
x-request-id: 7f3a91c2is enough for you to find the full story in the logs.
Example 4 · Finding errors in a time window, then one request
import java.time.Instant;import java.util.List;
record LogLine(Instant time, String level, String requestId, String message) {}
public class LogSearchDemo { public static void main(String[] args) { List<LogLine> logs = List.of( new LogLine(Instant.parse("2026-10-16T08:20:11Z"), "ERROR", "a01", "Payment gateway timeout"), new LogLine(Instant.parse("2026-10-16T08:34:58Z"), "INFO", "c77", "Listed page 0 of products"), new LogLine(Instant.parse("2026-10-16T08:35:02Z"), "INFO", "7f3a91c2", "Placing order for customer 1"), new LogLine(Instant.parse("2026-10-16T08:35:02Z"), "ERROR", "7f3a91c2", "Unknown column 'gift_note'"), new LogLine(Instant.parse("2026-10-16T08:36:40Z"), "WARN", "d09", "Slow query: 1.8 s"), new LogLine(Instant.parse("2026-10-16T08:51:00Z"), "ERROR", "e12", "Token expired"));
// "Orders failed at about 14:05 IST" = 08:35 UTC: look from 08:30 to 08:40 Instant from = Instant.parse("2026-10-16T08:30:00Z"); Instant to = Instant.parse("2026-10-16T08:40:00Z");
System.out.println("ERROR and WARN between 08:30 and 08:40 UTC:"); logs.stream() .filter(l -> !l.time().isBefore(from) && l.time().isBefore(to)) .filter(l -> l.level().equals("ERROR") || l.level().equals("WARN")) .forEach(l -> System.out.println(" " + l.time() + " " + l.level() + " [" + l.requestId() + "] " + l.message()));
System.out.println("Everything for request 7f3a91c2:"); logs.stream() .filter(l -> l.requestId().equals("7f3a91c2")) .forEach(l -> System.out.println(" " + l.level() + " " + l.message())); }}ERROR and WARN between 08:30 and 08:40 UTC: 2026-10-16T08:35:02Z ERROR [7f3a91c2] Unknown column 'gift_note' 2026-10-16T08:36:40Z WARN [d09] Slow query: 1.8 s Everything for request 7f3a91c2: INFO Placing order for customer 1 ERROR Unknown column 'gift_note'
What this code does
- The window keeps only the minutes around the report; the older payment error and the later token error are left out. India is UTC+05:30, so 14:05 IST is 08:35 in the logs.
- Following the request id shows the whole story of one failed order: it started normally and failed on a database column, which points straight at the schema.
Investigate in three steps: narrow the time window around the problem, filter by level, then follow one request with the requestId from the error line or from the X-Request-Id header of the user's failed response.
The filter reads X-Request-Id (or creates an id), returns it in the response header and removes it from the MDC in finally. Skipping MDC.remove is the common mistake: Tomcat reuses threads, so the next request would log the old id.
Order of execution
Investigate a failure
Tap the steps in the order you would take them.
Reading a stack trace and matching it to the deploy
The root cause is the deepest problem in a chain of exceptions, shown by the last Caused by: line of a stack trace. Fixing a higher line only treats a symptom.
A production stack trace lists the exception and then its causes. The program below walks to the last Caused by: and compares the first error time with the deploy time.
Example 5 · From a stack trace to its cause and the deploy time
import java.sql.SQLSyntaxErrorException;import java.time.Instant;import java.util.List;
public class RootCauseDemo { static Throwable rootCause(Throwable t) { while (t.getCause() != null && t.getCause() != t) { t = t.getCause(); } return t; }
public static void main(String[] args) { Exception error = new IllegalStateException("Order 0 could not be saved", new RuntimeException("could not execute statement", new SQLSyntaxErrorException("Unknown column 'gift_note' in 'field list'")));
for (Throwable t = error; t != null; t = t.getCause()) { System.out.println((t == error ? "" : "Caused by: ") + t); } System.out.println("Root cause: " + rootCause(error).getMessage());
Instant deployFinished = Instant.parse("2026-10-16T08:31:40Z"); List<Instant> errorTimes = List.of( Instant.parse("2026-10-16T08:32:05Z"), Instant.parse("2026-10-16T08:33:10Z"), Instant.parse("2026-10-16T08:35:02Z")); long before = errorTimes.stream().filter(t -> t.isBefore(deployFinished)).count(); long after = errorTimes.size() - before; System.out.println("Errors before deploy: " + before + ", after: " + after + (before == 0 && after > 0 ? " -> suspect the new release" : "")); }}java.lang.IllegalStateException: Order 0 could not be saved Caused by: java.lang.RuntimeException: could not execute statement Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'gift_note' in 'field list' Root cause: Unknown column 'gift_note' in 'field list' Errors before deploy: 0, after: 3 -> suspect the new release
What this code does
- The chain prints like the
Caused by:lines of a real stack trace; the last cause names the actual problem, a column the code expects but the database does not have. - Every error came after the deploy finished at 08:31:40 and none before, so the new release is the first suspect: perhaps its code needs a migration that did not run.
Read a stack trace from the bottom Caused by: upwards: the last cause is usually the real problem, and the lines above it show which ShopLite class and method were running.
Then compare times. An error that starts a minute after a deploy, with none before, makes the new release the prime suspect, which leads to the next lesson, the rollback. Errors that were already there before the deploy point elsewhere: the database, traffic or an outside service.
Find the bug
Find the root cause
Click the line that shows the real problem.
Which line is the real problem?
Round 1 of 2Next step
Check your understanding
11 quick questions