Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LOG4J2-2120: Json escaping handles newline correctly #133

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,11 @@ public static void trimToMaxSize(final StringBuilder stringBuilder, final int ma
public static void escapeJson(final StringBuilder toAppendTo, final int start) {
for (int i = toAppendTo.length() - 1; i >= start; i--) { // backwards: length may change
final char c = toAppendTo.charAt(i);
if (Character.isISOControl(c)) {
if (c == '\n') {
// Json string newline character must be encoded as literal "\n"
toAppendTo.setCharAt(i, '\\');
toAppendTo.insert(i + 1, 'n');
} else if (Character.isISOControl(c)) {
// all iso control characters are in U+00xx
toAppendTo.setCharAt(i, '\\');
toAppendTo.insert(i + 1, "u0000");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ public void testJSONEscape() {
assertEquals(expected, result);
}

@Test
public void testJSONEscapeNewline() {
final String testMsg = "hello\nworld";
final StringMapMessage msg = new StringMapMessage();
msg.put("one\ntwo", testMsg);
final String result = msg.getFormattedMessage(new String[]{"JSON"});
final String expected = "{\"one\\ntwo\":\"hello\\nworld\"}";
assertEquals(expected, result);
}

@Test
public void testJava() {
final String testMsg = "Test message {}";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ public void testJsonEscaping() throws Exception {
final LogEvent event = Log4jLogEvent.newBuilder()
.setLoggerName(getClass().getName())
.setLevel(Level.DEBUG)
.setMessage(new SimpleMessage("This string contains \"quotes\" and \\ backslash and \u001F control"))
.setMessage(new SimpleMessage("This string contains \"quotes\" and \\ backslash and \u001F control and\nnewline"))
.build();
final String expected = "This string contains \\\"quotes\\\" and \\\\ backslash and \\u001F control";
final String expected = "This string contains \\\"quotes\\\" and \\\\ backslash and \\u001F control and\\nnewline";
final StringBuilder sb = new StringBuilder();
final LoggerContext ctx = LoggerContext.getContext();
final String[] options = new String[]{"%msg", "JSON"};
Expand Down