Use parameterized logging with placeholders (`{}`) instead of string concatenation for better performance and readability. When logging exceptions, pass the exception object as a separate parameter to the logger rather than including its message in the format string.
Use parameterized logging with placeholders ({}
) instead of string concatenation for better performance and readability. When logging exceptions, pass the exception object as a separate parameter to the logger rather than including its message in the format string.
Why this matters:
Examples:
❌ Avoid string concatenation:
logger.debug("Fail to read the clean shutdown file in " + cleanShutdownFile.toPath() + ":" + e);
LOGGER.error(format("Encountered error while deleting %s", file.getAbsolutePath()));
✅ Use parameterized logging:
logger.debug("Fail to read the clean shutdown file in {}:{}", cleanShutdownFile.toPath(), e);
LOGGER.error("Encountered error while deleting {}", file.getAbsolutePath(), e);
❌ Avoid including exception message in format string:
String msg = String.format("Deserializing record %s from %s failed due to: %s", record, tp, ex.getMessage());
LOG.error(msg);
✅ Pass exception as separate parameter:
String msg = String.format("Deserializing record %s from %s failed", record, tp);
LOG.error(msg, ex);
This approach ensures optimal performance, provides complete exception information, and maintains consistent logging patterns across the codebase.
Enter the URL of a public GitHub repository