Skip to content

Commit 99c7608

Browse files
committed
Replace both EOL and control characters
1 parent c0f79ee commit 99c7608

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

spring-core/src/main/java/org/springframework/core/log/LogFormatUtils.java

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.core.log;
1818

1919
import java.util.function.Function;
20+
import java.util.regex.Pattern;
2021

2122
import org.apache.commons.logging.Log;
2223

@@ -35,10 +36,15 @@
3536
*/
3637
public abstract class LogFormatUtils {
3738

39+
private static final Pattern NEWLINE_PATTERN = Pattern.compile("[\n\r]");
40+
41+
private static final Pattern CONTROL_CHARACTER_PATTERN = Pattern.compile("\\p{Cc}");
42+
43+
3844
/**
3945
* Convenience variant of {@link #formatValue(Object, int, boolean)} that
4046
* limits the length of a log message to 100 characters and also replaces
41-
* newline characters if {@code limitLength} is set to "true".
47+
* newline and control characters if {@code limitLength} is set to "true".
4248
* @param value the value to format
4349
* @param limitLength whether to truncate the value at a length of 100
4450
* @return the formatted value
@@ -53,10 +59,13 @@ public static String formatValue(@Nullable Object value, boolean limitLength) {
5359
* compacting it into a single line when {@code replaceNewLines} is set.
5460
* @param value the value to be formatted
5561
* @param maxLength the max length, after which to truncate, or -1 for unlimited
56-
* @param replaceNewlines whether to replace newline characters with placeholders
62+
* @param replaceNewlinesAndControlCharacters whether to replace newline and
63+
* control characters with placeholders
5764
* @return the formatted value
5865
*/
59-
public static String formatValue(@Nullable Object value, int maxLength, boolean replaceNewlines) {
66+
public static String formatValue(
67+
@Nullable Object value, int maxLength, boolean replaceNewlinesAndControlCharacters) {
68+
6069
if (value == null) {
6170
return "";
6271
}
@@ -70,8 +79,9 @@ public static String formatValue(@Nullable Object value, int maxLength, boolean
7079
if (maxLength != -1) {
7180
result = (result.length() > maxLength ? result.substring(0, maxLength) + " (truncated)..." : result);
7281
}
73-
if (replaceNewlines) {
74-
result = result.replace("\n", "<LF>").replace("\r", "<CR>");
82+
if (replaceNewlinesAndControlCharacters) {
83+
result = NEWLINE_PATTERN.matcher(result).replaceAll("<EOL>");
84+
result = CONTROL_CHARACTER_PATTERN.matcher(result).replaceAll("?");
7585
}
7686
if (value instanceof CharSequence) {
7787
result = "\"" + result + "\"";

0 commit comments

Comments
 (0)