LogFormatUtils.formatValue leniently handles toString() exceptions

Issue: SPR-17397
This commit is contained in:
Juergen Hoeller 2018-10-18 18:04:32 +02:00
parent da23505e94
commit 7ff938b3ef
1 changed files with 21 additions and 10 deletions

View File

@ -30,6 +30,7 @@ import org.springframework.lang.Nullable;
* with other Commons Logging bridges. * with other Commons Logging bridges.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 5.1 * @since 5.1
*/ */
public abstract class LogFormatUtils { public abstract class LogFormatUtils {
@ -41,14 +42,24 @@ public abstract class LogFormatUtils {
* @param value the value to format * @param value the value to format
* @param limitLength whether to truncate large formatted values (over 100) * @param limitLength whether to truncate large formatted values (over 100)
* @return the formatted value * @return the formatted value
* @since 5.1
*/ */
public static String formatValue(@Nullable Object value, boolean limitLength) { public static String formatValue(@Nullable Object value, boolean limitLength) {
if (value == null) { if (value == null) {
return ""; return "";
} }
String s = (value instanceof CharSequence ? "\"" + value + "\"" : value.toString()); String str;
return (limitLength && s.length() > 100 ? s.substring(0, 100) + " (truncated)..." : s); if (value instanceof CharSequence) {
str = "\"" + value + "\"";
}
else {
try {
str = value.toString();
}
catch (Throwable ex) {
str = ex.toString();
}
}
return (limitLength && str.length() > 100 ? str.substring(0, 100) + " (truncated)..." : str);
} }
/** /**
@ -56,12 +67,12 @@ public abstract class LogFormatUtils {
* messages) at TRACE vs DEBUG log levels. Effectively, a substitute for: * messages) at TRACE vs DEBUG log levels. Effectively, a substitute for:
* <pre class="code"> * <pre class="code">
* if (logger.isDebugEnabled()) { * if (logger.isDebugEnabled()) {
* String s = logger.isTraceEnabled() ? "..." : "..."; * String str = logger.isTraceEnabled() ? "..." : "...";
* if (logger.isTraceEnabled()) { * if (logger.isTraceEnabled()) {
* logger.trace(s); * logger.trace(str);
* } * }
* else { * else {
* logger.debug(s); * logger.debug(str);
* } * }
* } * }
* </pre> * </pre>