Why Using logger.info with JSON Serialization Can Crash Your Production Performance
This article explains how calling LOGGER.info with JSON serialization in a production environment set to WARN can waste CPU cycles, cause latency spikes, and even bring down high‑concurrency systems, and it offers a simple guard‑clause solution.
Problem Code
In a production environment where the log level is set to warn, the following line of code appears:
LOGGER.info("the DTO info: {}", JSON.toJSONString(DTO));The author asks whether this code has any issues.
Root Cause Analysis
Two important points need attention:
The log level used in the code is info, while the production environment only outputs warn and above, so the log line will never be printed.
The logging call performs a JSON serialization of DTO before the log is actually emitted.
If DTO is a small object, the serialization overhead is negligible. However, for large objects (e.g., 10 KB or 100 KB), even fast JSON libraries can take hundreds of milliseconds and consume significant CPU, which is unacceptable in high‑concurrency systems.
Some may wonder why the code runs at all if the log level is info. In SLF4J, the logger.info(String format, Object arg) method receives an Object argument. In this case the argument is the result of JSON.toJSONString(DTO), which means the JSON conversion happens before the logger decides whether to output the message. The info call only takes effect when the log is actually written.
public void info(String format, Object arg);Solution
To avoid unnecessary serialization, add a log‑level guard before the logging statement. The author also provides a script that scans Java code for logger.info() calls containing JSON serialization and enforces the presence of a preceding logger.isInfoEnabled() check, which can be integrated into CI/CD pipelines.
if (LOGGER.isInfoEnabled()) {
LOGGER.info("the DTO info: {}", JSON.toJSONString(DTO));
}If the logged message does not involve expensive operations, the guard is unnecessary, as shown in the following example:
String reqId = "...";
String msg = "...";
LOGGER.info("the DTO info: {}", msg);--- END ---
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
