Skip to content

Commit

Permalink
fix: fix #1
Browse files Browse the repository at this point in the history
  • Loading branch information
dekobon committed Nov 29, 2021
1 parent 8f0c600 commit 50d5b4c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/main/java/log4j/layout/bunyan/LogEventJsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ private boolean writeAdditionalFields(final JsonWriter writer, LogEvent event) {
}

final ReadOnlyStringMap contextData = event.getContextData();
if (noTrailingComma && !contextData.isEmpty()) {
if (noTrailingComma && this.includeAllContextProperties && !contextData.isEmpty()) {
writer.writeByte(JsonWriter.COMMA);
}

Expand Down
26 changes: 26 additions & 0 deletions src/test/java/log4j/layout/bunyan/LogOutputTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.apache.logging.log4j.core.util.KeyValuePair;
import org.apache.logging.log4j.message.FormattedMessage;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.spi.DefaultThreadContextStack;
import org.apache.logging.log4j.util.SortedArrayStringMap;
import org.apache.logging.log4j.util.StringMap;
Expand Down Expand Up @@ -157,6 +158,31 @@ void canLogNaughtyStrings() throws IOException {
}
}

/**
* Reproduces bug where an extra comma is inserted despite
* properties=false.
*
* @see <a href="https://github.com/dekobon/log4j2-bunyan-layout/issues/1">#1</a>
*/
@Test
void jsonIsValidIfPropertiesAreDisabled() throws IOException {
KeyValuePair keyValuePair = new KeyValuePair(
"traceId", "$${ctx:traceId:-}");
final BunyanJsonLayout layout = instance(
new KeyValuePair[] { keyValuePair },
null, false);
final MutableLogEvent event = new MutableLogEvent();
event.setTimeMillis(System.currentTimeMillis());
event.setLoggerName(getClass().getName());
event.setLevel(Level.INFO);
event.setMessage(new SimpleMessage("hello"));
StringMap contextData = new SortedArrayStringMap();
contextData.putValue("traceId", "c0160ca6-50ba-11ec-a64b-fbca1ea30083");
event.setContextData(contextData);
String json = fauxLogger.formatEvent(event, layout);
validateEvent(event, json);
}

void validateEvent(final LogEvent event, final String json) throws IOException {
if (event.getLevel().equals(Level.OFF)) {
assertTrue(json.isEmpty(), "Nothing should be logged when level is OFF");
Expand Down

0 comments on commit 50d5b4c

Please sign in to comment.