Lesson 6 of 8
Logging - SLF4J, Logback & Log Levels
Production applications must log - structured, level-filtered logs are essential for debugging, monitoring and diagnostics. SLF4J is the logging API (like JDBC for databases); Logback is the most common implementation. Never use System.out.println in production code.
SLF4J + Logback - Structured Logging
import org.slf4j.*;
// SLF4J Logger - one per class, static final
public class LibraryService {
private static final Logger log = LoggerFactory.getLogger(LibraryService.class);
public BorrowRecord checkout(String isbn, String memberId) {
// ── Log levels - use the right level ────────────────────
log.trace("checkout called: isbn={} member={}", isbn, memberId); // very detailed (dev only)
log.debug("Fetching book from repo: {}", isbn); // debugging info
log.info("Checkout request: isbn={} member={}", isbn, memberId); // normal operations
log.warn("Book nearly overdue: isbn={}", isbn); // something to watch
log.error("checkout failed for isbn={}: {}", isbn, "error details"); // failure
// ── {} placeholders - lazy evaluation, NO string concat ──
// ✅ log.debug("Processing book: {}", book) - book.toString() called ONLY if DEBUG enabled
// ❌ log.debug("Processing book: " + book) - string always constructed (wasteful)
// ── Exception logging - ALWAYS use two-arg form ──────────
try {
return doCheckout(isbn, memberId);
} catch (BookNotFoundException e) {
log.warn("Book not found during checkout: isbn={}", isbn); // expected - warn
throw e;
} catch (Exception e) {
log.error("Unexpected error during checkout: isbn={} member={}", isbn, memberId, e);
// ↑ THIRD arg = exception: logback will print full stack trace
throw new LibraryException("Checkout failed", "CHECKOUT_ERROR", e);
}
}
private BorrowRecord doCheckout(String isbn, String memberId) { return null; }
}
// logback.xml - configure logging (src/main/resources/logback.xml)
/*
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/library.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/library.%d{yyyy-MM-dd}.log.gz</fileNamePattern>
<maxHistory>30</maxHistory> <!-- keep 30 days -->
</rollingPolicy>
<encoder>
<pattern>%d{ISO8601} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- Dev profile: DEBUG for our code, INFO for libraries -->
<logger name="com.priygop" level="DEBUG"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE"/>
</root>
</configuration>
*/Log Levels & Config Profiles
- TRACE - Most verbose. Flow tracing, variable values at every step. Dev only. Never in prod.
- DEBUG - Diagnostic details. SQL queries, calculated values, branch decisions. Dev/staging.
- INFO - Normal operation milestones. Service start/stop, checkout completed, cron ran. Production standard.
- WARN - Unexpected condition, not yet an error. Near-timeout, retried, deprecated usage.
- ERROR - Failure requiring attention. Exceptions, failed operations, data integrity issues.
- Config profiles: logback-dev.xml (DEBUG, console with colours), logback-prod.xml (INFO, rolling file, JSON format for log aggregators).
Quick Quiz
Tip
Tip
Practice Logging SLF4J Logback Log Levels in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Logging - SLF4J, Logback & Log Levels
Practice Task
Note
Practice Task - (1) Write a working example of Logging SLF4J Logback Log Levels from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Logging SLF4J Logback Log Levels is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Production applications must log - structured, level-filtered logs are essential for debugging, monitoring and diagnostics.
- TRACE - Most verbose. Flow tracing, variable values at every step. Dev only. Never in prod.
- DEBUG - Diagnostic details. SQL queries, calculated values, branch decisions. Dev/staging.
- INFO - Normal operation milestones. Service start/stop, checkout completed, cron ran. Production standard.
Finished this lesson?