Skip to content

Commit b10e95f

Browse files
authored
Trim the JSON source in indexing slow logs elastic#38156 Backport#38081
The '{' as a first character in log line is causing problems for beats when parsing plaintext logs. This can happen if the submitted document has an additional '\n' at the beginning and we are not reformatting. Trimming the source part of a SlogLog solves that and keeps the logs readable. relates elastic#38080 backport elastic#38081
1 parent e0b32cf commit b10e95f

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

server/src/main/java/org/elasticsearch/index/IndexingSlowLog.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ public String toString() {
194194
}
195195
try {
196196
String source = XContentHelper.convertToJson(doc.source(), reformat, doc.getXContentType());
197-
sb.append(", source[").append(Strings.cleanTruncate(source, maxSourceCharsToLog)).append("]");
197+
sb.append(", source[").append(Strings.cleanTruncate(source, maxSourceCharsToLog).trim()).append("]");
198198
} catch (IOException e) {
199199
sb.append(", source[_failed_to_convert_[").append(e.getMessage()).append("]]");
200200
/*

server/src/test/java/org/elasticsearch/index/IndexingSlowLogTests.java

+17
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
import java.io.UncheckedIOException;
3939

4040
import static org.hamcrest.Matchers.containsString;
41+
import static org.hamcrest.Matchers.equalTo;
4142
import static org.hamcrest.Matchers.hasToString;
4243
import static org.hamcrest.Matchers.instanceOf;
4344
import static org.hamcrest.Matchers.not;
@@ -127,6 +128,22 @@ public void testReformatSetting() {
127128
assertTrue(log.isReformat());
128129
}
129130

131+
public void testReformatIsFalseAndSourceIsTrim() {
132+
String json = "\n\n{ \"fieldName\": 123 } \n ";
133+
BytesReference source = new BytesArray(json);
134+
ParsedDocument pd = new ParsedDocument(new NumericDocValuesField("version", 1),
135+
SeqNoFieldMapper.SequenceIDFields.emptySeqID(), "id",
136+
"test", null, null, source, XContentType.JSON, null);
137+
Index index = new Index("foo", "123");
138+
// Turning off reformatting so the document is in logs as provided
139+
SlowLogParsedDocumentPrinter p = new SlowLogParsedDocumentPrinter(index, pd, 10, false, 1000);
140+
String logLine = p.toString();
141+
142+
//expect the new lines and white characters to be trimmed
143+
assertThat(logLine, containsString("source[{"));
144+
assertThat(logLine.split("\n").length, equalTo(1));
145+
}
146+
130147
public void testLevelSetting() {
131148
SlowLogLevel level = randomFrom(SlowLogLevel.values());
132149
IndexMetaData metaData = newIndexMeta("index", Settings.builder()

0 commit comments

Comments
 (0)