Skip to content

Commit

Permalink
When logpayload=true, ExchangeLogger must log request payload (best e…
Browse files Browse the repository at this point in the history
…ffort)
  • Loading branch information
rmannibucau committed Mar 21, 2023
1 parent 46dbeba commit 3833532
Showing 1 changed file with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,18 @@

import io.yupiik.fusion.httpclient.core.listener.RequestListener;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.Flow;
import java.util.logging.Logger;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
* Usage:
* <p>
Expand Down Expand Up @@ -56,6 +62,44 @@ protected String toLogMessage(final Data before, final HttpRequest request, fina
return "#" + before.count + ", " +
"Request: '" + request.method() + " " + request.uri() + "' took " +
clock.instant().minusMillis(before.instant.toEpochMilli()).toEpochMilli() + "ms\n" +
(logPayload ? request.bodyPublisher()
.map(it -> {
final var out = new ByteArrayOutputStream();
it.subscribe(new Flow.Subscriber<>() {
@Override
public void onSubscribe(final Flow.Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}

@Override
public void onNext(final ByteBuffer item) {
int l = item.remaining();
final var buffer = new byte[l];
item.get(buffer, 0, l);
try {
out.write(buffer);
} catch (final IOException e) {
// no-op
}
}

@Override
public void onError(final Throwable throwable) {
try {
out.write("<can't extract payload>".getBytes(UTF_8));
} catch (final IOException e) {
// no-op
}
}

@Override
public void onComplete() {
// no-op
}
});
return "\nPayload:\n" + out.toString(UTF_8);
})
.orElse("") : "") +
"Response: " + (error != null ? "[ERROR] " + error.getMessage() : ("HTTP " + response.statusCode())) +
(logPayload ? "\nPayload:\n" + (response == null ? "-" : response.body()) : "");
}
Expand Down

0 comments on commit 3833532

Please sign in to comment.