Skip to content

Commit 50f6db2

Browse files
committed
Replace both EOL and control characters
1 parent 24ebb5e commit 50f6db2

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

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

Lines changed: 17 additions & 6 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,9 +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
/**
39-
* Variant of {@link #formatValue(Object, int, boolean)} and a convenience
40-
* method that truncates at 100 characters when {@code limitLength} is set.
45+
* Convenience variant of {@link #formatValue(Object, int, boolean)} that
46+
* limits the length of a log message to 100 characters and also replaces
47+
* newline and control characters if {@code limitLength} is set to "true".
4148
* @param value the value to format
4249
* @param limitLength whether to truncate the value at a length of 100
4350
* @return the formatted value
@@ -52,10 +59,13 @@ public static String formatValue(@Nullable Object value, boolean limitLength) {
5259
* compacting it into a single line when {@code replaceNewLines} is set.
5360
* @param value the value to be formatted
5461
* @param maxLength the max length, after which to truncate, or -1 for unlimited
55-
* @param replaceNewlines whether to replace newline characters with placeholders
62+
* @param replaceNewlinesAndControlCharacters whether to replace newline and
63+
* control characters with placeholders
5664
* @return the formatted value
5765
*/
58-
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+
5969
if (value == null) {
6070
return "";
6171
}
@@ -69,8 +79,9 @@ public static String formatValue(@Nullable Object value, int maxLength, boolean
6979
if (maxLength != -1) {
7080
result = (result.length() > maxLength ? result.substring(0, maxLength) + " (truncated)..." : result);
7181
}
72-
if (replaceNewlines) {
73-
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("?");
7485
}
7586
if (value instanceof CharSequence) {
7687
result = "\"" + result + "\"";

0 commit comments

Comments
 (0)