17
17
package org .springframework .core .log ;
18
18
19
19
import java .util .function .Function ;
20
+ import java .util .regex .Pattern ;
20
21
21
22
import org .apache .commons .logging .Log ;
22
23
35
36
*/
36
37
public abstract class LogFormatUtils {
37
38
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
+
38
44
/**
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".
41
48
* @param value the value to format
42
49
* @param limitLength whether to truncate the value at a length of 100
43
50
* @return the formatted value
@@ -52,10 +59,13 @@ public static String formatValue(@Nullable Object value, boolean limitLength) {
52
59
* compacting it into a single line when {@code replaceNewLines} is set.
53
60
* @param value the value to be formatted
54
61
* @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
56
64
* @return the formatted value
57
65
*/
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
+
59
69
if (value == null ) {
60
70
return "" ;
61
71
}
@@ -69,8 +79,9 @@ public static String formatValue(@Nullable Object value, int maxLength, boolean
69
79
if (maxLength != -1 ) {
70
80
result = (result .length () > maxLength ? result .substring (0 , maxLength ) + " (truncated)..." : result );
71
81
}
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 ("?" );
74
85
}
75
86
if (value instanceof CharSequence ) {
76
87
result = "\" " + result + "\" " ;
0 commit comments