Logging
logging logs are how a running java service tells you what it's doing. the de-facto stack is slf4j (the api) + logback
Introduction
Logs are how a running Java service tells you what it's doing. The de-facto stack is SLF4J (the API) + Logback or Log4j2 (the implementation).
Informative example
Idiomatic logging:
import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class OrderService {private static final Logger log = LoggerFactory.getLogger(OrderService.class);public void place(String customer, int cents) {log.info("Placing order customer={} cents={}", customer, cents);try {// ...} catch (Exception e) {log.error("Order failed customer={} cents={}", customer, cents, e); // include throwable LAST}}}
Best practices
- Use parameterised messages (
{}) — avoids string concat when level is disabled. - Log at the right level: ERROR is for actionable failures, INFO for business events, DEBUG for diagnostics.
- Add a correlation ID (MDC) so you can trace a request across services.
Common mistakes
- Logging passwords, tokens or PII — GDPR fines start at 4% of revenue.
System.out.printlnin production code — bypasses log config.
Purpose of this lesson
Master Logging so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Logging.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when logging is the right tool for the problem.
Useful template
SLF4J with Logback
private static final Logger log = LoggerFactory.getLogger(MyService.class);log.info("User {} placed order {}", userId, orderId);
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Logging daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Logging in one minute.
Q2When would you avoid Logging?
Summary
In this lesson you learned Logging — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.