Effective Logging Practices for Java Backend Services
The article discusses common challenges with missing logs in production, proposes practical solutions such as adding machine identifiers via Nginx headers and embedding user information with Log4j's MDC, and outlines concise logging guidelines to improve traceability and performance analysis for Java backend systems.
The author revisits previous articles on poor Java code and interface/controller standards, then highlights a frequent issue: production bugs that cannot be reproduced due to insufficient logging, especially in large clusters where locating the responsible node and user actions is painful.
Two essential logging requirements are proposed: (1) the ability to identify the specific machine handling a request, and (2) the ability to capture what the user did. To satisfy the first requirement, the Nginx configuration is adjusted to return the processing node in response headers, with a simple example configuration shown.
For the second requirement, the author recommends using Log4j's MDC (Mapped Diagnostic Context) to store user information per request, clearing it after the filter to avoid thread‑pool contamination. Sample filter code and MDC usage are illustrated.
After establishing these foundations, three concise logging rules are defined for developers: (1) all modifications (including additions) must be logged, ensuring data changes are traceable; (2) conditional branches must log condition values and important parameters, exemplified by printing a userType value that determines code flow; (3) when processing large data volumes, log the amount of data processed to aid performance analysis.
The article also presents example log outputs and emphasizes that log levels are less critical than consistent logging practices. It concludes with advice for newcomers: rely on logs rather than debugger, review logs before committing code, and treat logging as an integral part of functional development.
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.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.
