Skip to content

Commit

Permalink
Synchronize JsonLayout
Browse files Browse the repository at this point in the history
The doLayout method used a single JsonEventWriter field in a
non-thread-safe way. Consequently, writing logs from multiple threads
would corrupt its buffer and send malformed JSON to Loki.

By synchronizing the method, only a single thread accesses the buffer at
a time, guaranteeing that its content remains valid JSON.
  • Loading branch information
knittl committed Jun 30, 2024
1 parent 2f3928d commit 79e9a5e
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public class JsonLayout extends ContextAwareBase implements Layout<ILoggingEvent
private List<JsonProvider<ILoggingEvent>> customProviders = new ArrayList<>();

@Override
public String doLayout(ILoggingEvent event) {
public synchronized String doLayout(ILoggingEvent event) {
var standard = providers.iterator();
var custom = customProviders.iterator();
var firstFieldWritten = false;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
package com.github.loki4j.logback;

import java.util.*;

import static com.github.loki4j.logback.Generators.*;
import static org.junit.Assert.*;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import org.junit.Test;
Expand Down Expand Up @@ -97,10 +103,76 @@ protected void writeExactlyOneField(JsonEventWriter writer, ILoggingEvent event)
layout.stop();
}

private <T extends JsonProvider<?>> T disable(Supplier<T> ctor) {
var provider = ctor.get();
@Test
public void testThreadSafety() throws Exception {
class Result {
final String expected;
final String actual;

public Result(final String expected, final String actual) {
this.expected = expected;
this.actual = actual;
}
}

final List<Result> results = Collections.synchronizedList(new ArrayList<>());

final var layout = jsonMsgLayout();
try {
layout.setLogLevel(disable(LogLevelJsonProvider::new));
layout.setLoggerName(disable(LoggerNameJsonProvider::new));
layout.setTimestamp(disable(TimestampJsonProvider::new));

layout.start();

// ready...
final CountDownLatch latch = new CountDownLatch(1);
final ExecutorService executorService = Executors.newFixedThreadPool(16);
// set...
for (int i = 0; i < 128; i++) {
final int threadId = i;
executorService.submit(() -> {
awaitLatch(latch);
final var event = loggingEvent(
100L,
Level.INFO,
"io.test.TestApp",
"main-" + threadId,
"log from thread #" + threadId,
null);
final String formatted = layout.doLayout(event);
final String expected = String.format("{'thread_name':'main-%s','message':'log from thread #%s'}", threadId, threadId)
.replace('\'', '"');
results.add(new Result(expected, formatted));
});
}

// go!
latch.countDown();
executorService.shutdown();
assertTrue(executorService.awaitTermination(10L, TimeUnit.SECONDS));

for (final Result result : results) {
assertEquals(result.expected, result.actual);
}
} finally {
layout.stop();
}
}

private static void awaitLatch(final CountDownLatch latch) {
try {
latch.await();
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
}

private <T extends JsonProvider<?>> T disable(final Supplier<T> ctor) {
final var provider = ctor.get();
provider.setEnabled(false);
return provider;
}

}

0 comments on commit 79e9a5e

Please sign in to comment.