Skip to content

Commit

Permalink
strip leading and trailing, but do not squash inner whitespaces (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
fupgang committed Feb 29, 2024
1 parent 7973aba commit 66261c7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 26 deletions.
31 changes: 5 additions & 26 deletions src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
Original file line number Diff line number Diff line change
Expand Up @@ -439,33 +439,12 @@ protected String normalizeShortMessage(final String shortMessage) {
}

private String sanitizeShortMessage(final String sanitizedShortMessage) {
if (sanitizedShortMessage.isEmpty()) {
return sanitizedShortMessage;
String stripped = sanitizedShortMessage.strip();
if(getMaxShortMessageLength() != 0 && stripped.length() > getMaxShortMessageLength()) {
return stripped.substring(0, getMaxShortMessageLength());
} else {
return stripped;
}

final int len = maxShortMessageLength == 0
? sanitizedShortMessage.length()
: Math.min(sanitizedShortMessage.length(), maxShortMessageLength);
final char[] tmp = new char[len];

int iDst = 0;
boolean whitspaceLast = false;
boolean whitespaceStart = true;
for (int iSrc = 0; iSrc < sanitizedShortMessage.length() && iDst < tmp.length; iSrc++) {
final char c = sanitizedShortMessage.charAt(iSrc);
if (Character.isWhitespace(c)) {
if (!whitespaceStart && !whitspaceLast) {
tmp[iDst++] = ' ';
}
whitspaceLast = true;
} else {
tmp[iDst++] = c;
whitspaceLast = false;
whitespaceStart = false;
}
}

return new String(tmp, 0, iDst).trim();
}

protected String buildShortMessage(final ILoggingEvent event) {
Expand Down
30 changes: 30 additions & 0 deletions src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,36 @@ void shortenShortMessageDefault() {
.isEqualTo(expectedShortMessage);
}

@Test
void doNotSquashInnerWhitespaces() {
final String shortMessage = "unknown operand:\nx=1 § 1\n ^";

final GelfEncoder gelfEncoder = new GelfEncoder();

final String actual = gelfEncoder.normalizeShortMessage(shortMessage);
assertThat(actual).isEqualTo(shortMessage);
}

@Test
void stripLeadingAndTrailingWhitespaces() {
final String shortMessage = "\t [---] \n";

final GelfEncoder gelfEncoder = new GelfEncoder();

final String actual = gelfEncoder.normalizeShortMessage(shortMessage);
assertThat(actual).isEqualTo("[---]");
}

@Test
void shortenAfterStrippingWhitespaces() {
final String shortMessage = "\t \n" + "A".repeat(250) + "\t \n";

final GelfEncoder gelfEncoder = new GelfEncoder();

final String actual = gelfEncoder.normalizeShortMessage(shortMessage);
assertThat(actual).hasSize(250).doesNotContainAnyWhitespaces();
}

@Test
void exception() {
encoder.start();
Expand Down

0 comments on commit 66261c7

Please sign in to comment.