• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


27 Feb, 2025

Updated at 21 Mar, 2025

How to limit string-length in a logged message?

Consider the logging call below:

            logger.debug("Neither {} nor {} in {}",
                pattern1, pattern2,
                sql.substring(0, idx));

The intent is to cite only the beginning of the sql-string in the debug-message, so as not to spam the logs with the entire SQL-blobs.

This even works, but is suboptimal, because the new string is constructed -- by the sql.substring() -- even when the debug-logging is not enabled.

Programming in C and logging with the syslog(3), I would've used the printf(3) feature to limit the maximum size of the string printed. However, this does not work with log4j:

            logger.debug("Neither {} nor {} in %.*s",
                pattern1, pattern2,
                idx, sql);

Is there a similarly-efficient alternative? (I know, I can check logger.isDebugEnabled() myself, but that's ugly...)