Mastering Java Logging: Framework Choices, Level Rules, and Best Practices
This guide details how to select a Java logging framework, defines a decision tree for when to log, maps log levels (ERROR, WARN, INFO, DEBUG) to concrete scenarios, provides code‑handling principles, outlines prohibited logging patterns, and includes a quick reference for alerting rules.
Logging Framework Selection
All services must use SLF4J as the logging façade. The concrete implementation should be Logback or Log4j2. Direct dependencies on implementation classes such as ch.qos.logback.classic.Logger are prohibited.
Decision Tree: Should I Log?
Before invoking log.xxx, ask three questions. If the answer to all is “No”, do not log.
Will this log help troubleshoot the issue? Bad: log.info("start processing"); – no useful information. Good: log.info("Start processing Order, ID: {}", orderId); Does the log contain specific data or state? Bad: log.error("Error occurred");. Good:
log.error("Payment failed, User: {}, Reason: {}", userId, e.getMessage());Is the log needed for statistics or monitoring alerts? Example: counting daily "stock insufficient" exceptions or logging API response codes for monitoring.
Log Level Definitions and Mapping
ERROR
Meaning: Unexpected or business‑critical errors that may cause data inconsistency or service interruption. Action: Must be connected to monitoring alerts; developers must intervene immediately.
Must‑log scenarios:
System crashes (e.g., OutOfMemoryError, thread‑pool rejection).
Critical service unavailability (database, Redis, payment gateway).
Data consistency violations (transaction failure, amount mismatch).
Unexpected code bugs (NPE, ArrayIndexOutOfBoundsException, ClassCastException).
Fallback logic triggered (unreachable else branch).
Prohibited scenarios: Normal business validation failures (wrong password, insufficient stock) and transient recoverable spikes (first retry failure).
WARN
Meaning: Abnormal conditions that do not break core business but deserve attention.
Must‑log scenarios:
Predictable business exceptions (parameter validation, blacklist, rate limiting).
Non‑critical service degradation (recommendation service down, cache miss).
Retry attempts (first failure logged as WARN; final failure escalates to ERROR).
Resource threshold warnings (connection pool >80%, response time >2 s).
INFO
Meaning: Milestones of system operation for traceability and analytics.
Must‑log scenarios:
Core state transitions (order created, payment succeeded, shipment completed).
Key entry/exit points (API request summary, important method results).
Scheduled task start/end and processed record count.
Configuration changes (startup parameters, feature‑flag toggles).
Prohibited scenarios: Logging inside tight loops, meaningless step markers, or overly verbose object dumps.
DEBUG
Meaning: Fine‑grained details for development environments.
Action: Disabled in production; enable conditionally with log.isDebugEnabled() when heavy computation or serialization is involved.
Typical Code Scenarios
Exception handling principle: Either rethrow the exception or handle it and log once. Never swallow an exception or log it multiple times.
Scenario 1: Catch an exception that cannot be handled, abort the business flow, and log at the appropriate level.
Scenario 2: Catch an exception, perform degradation, then rethrow a business exception; log the original error before conversion.
Scenario 3: Incorrect practice – duplicate logging.
Implementation guidelines:
Do not log when simply rethrowing the same exception; let a global handler log it.
If converting a system error to a business warning, log the original error/warn before conversion.
Implement a single global fallback logger (e.g., @RestControllerAdvice) that logs BusinessException as WARN (without full stack) and unknown exceptions as ERROR with full stack trace.
Remote Call Logging
When acting as a client to third‑party services, always record a concise request/response summary at INFO level for traceability (e.g., endpoint, latency, status code).
Logging Blacklist
Avoid logging sensitive plaintext and uninformative messages.
Never log passwords, identity cards, or other personal data in clear text; apply masking (e.g., 138****8888).
Never log inside POJO getters/setters or toString() methods.
Never use System.out, System.err, or e.printStackTrace() in production.
Prefer placeholder syntax over string concatenation.
Do not log large objects or huge strings (e.g., entire file content, massive HTML). Extract key fields or use utilities such as Lombok’s @ToString.Exclude, custom safe‑print helpers, or AOP‑based sanitization.
Quick Reference (selected scenarios)
Database/Redis connection loss – log at ERROR, trigger immediate alert.
NullPointerException, ArrayIndexOutOfBounds, ClassCastException – log at ERROR, immediate alert.
Core business failure (e.g., payment failure) – log at ERROR, immediate alert.
Non‑core business failure (e.g., report query) – log at WARN, alert if frequency exceeds threshold.
Parameter validation error – log at WARN, alert on repeated occurrences.
Retry / degradation / circuit‑break – log at WARN, alert on repeated retries.
Process state change (order created, payment succeeded) – log at INFO, no alert.
RPC call summary – log at INFO, used for traceability, no alert.
Scheduled task start/end – log at INFO, monitor health.
SQL/debug information – log at DEBUG, disabled in production.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect-Kip
Daily architecture work and learning summaries. Not seeking lengthy articles—only real practical experience.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
