javabeginner
Java Logging with SLF4J and Logback
Configure structured logging with SLF4J: log levels, MDC context, JSON format, and best practices.
javaPress ⌘/Ctrl + Shift + C to copy
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class LoggingDemo {
// One logger per class
private static final Logger log = LoggerFactory.getLogger(LoggingDemo.class);
public void processOrder(String orderId, String userId) {
// Set context — appears in every log line
MDC.put("orderId", orderId);
MDC.put("userId", userId);
try {
log.info("Processing order");
// Parameterized logging (avoids string concatenation)
log.debug("Order details — amount: {}, items: {}", 99.99, 3);
// Log levels
log.trace("Detailed trace info"); // most verbose
log.debug("Debug info for development");
log.info("Business event: order processed");
log.warn("Potential issue: low inventory");
log.error("Failed to charge payment");
// Log with exception (stack trace)
try {
riskyOperation();
} catch (Exception e) {
log.error("Operation failed for order {}", orderId, e);
throw e;
}
log.info("Order completed successfully");
} finally {
MDC.clear(); // always clean up
}
}
// Conditional expensive logging
public void debugHeavy() {
if (log.isDebugEnabled()) {
// Only compute if debug is enabled
String expensive = computeExpensiveDebugInfo();
log.debug("Debug data: {}", expensive);
}
}
// Structured data
public void auditLog(String action, String resource) {
MDC.put("action", action);
MDC.put("resource", resource);
log.info("Audit event"); // with JSON formatter: {"action":"delete","resource":"user-123"}
MDC.remove("action");
MDC.remove("resource");
}
private void riskyOperation() { /* ... */ }
private String computeExpensiveDebugInfo() { return "data"; }
}Use Cases
- Application logging with contextual information
- Structured audit logging for compliance
- Performance-safe debug logging
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Structured JSON Logger
Build a structured logger with log levels, context, child loggers, and JSON output for Node.js services.
Best for: Application logging for production
#nodejs#logging
typescriptbeginner
Structured Request Logger Middleware
Express middleware that logs request/response details as structured JSON with timing information.
Best for: API monitoring
#express#logging
pythonintermediate
Structured Logging with structlog
Configure structlog for JSON-formatted structured logging with request context, timestamps, and log levels.
Best for: Application logging
#logging#structlog
pythonbeginner
Structured Logging for Data Pipelines
Use Loguru to emit structured JSON logs with contextual fields from ETL pipeline stages.
Best for: pipeline observability
#loguru#logging