Escape a string so it can be displayed in a readable format. Characters that may not be printable in some/all of the contexts in which log messages will be viewed will be escaped using Java \\uNNNN escaping. All control characters are escaped apart from horizontal tab (\\u0009), new line (\\u000
(final String input)
| 38 | * @return The escaped form of the input string |
| 39 | */ |
| 40 | @SuppressWarnings("null") // sb is not null when used |
| 41 | public static String escape(final String input) { |
| 42 | final int len = input.length(); |
| 43 | int i = 0; |
| 44 | int lastControl = -1; |
| 45 | StringBuilder sb = null; |
| 46 | while (i < len) { |
| 47 | char c = input.charAt(i); |
| 48 | if (Character.getType(c) == Character.CONTROL) { |
| 49 | if (!(c == '\t' || c == '\n' || c == '\r')) { |
| 50 | if (lastControl == -1) { |
| 51 | sb = new StringBuilder(len + 20); |
| 52 | } |
| 53 | sb.append(input.substring(lastControl + 1, i)); |
| 54 | sb.append(String.format("\\u%1$04x", Integer.valueOf(c))); |
| 55 | lastControl = i; |
| 56 | } |
| 57 | } |
| 58 | i++; |
| 59 | } |
| 60 | if (lastControl == -1) { |
| 61 | return input; |
| 62 | } else { |
| 63 | sb.append(input.substring(lastControl + 1, len)); |
| 64 | return sb.toString(); |
| 65 | } |
| 66 | } |
| 67 | } |