Last active
October 4, 2017 21:45
-
-
Save drobertduke/e48d08645ba872a933d192cd232bf3b7 to your computer and use it in GitHub Desktop.
A Java implementation of a gRPC client logging interceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.grpc.interceptor.logging; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import io.grpc.CallOptions; | |
import io.grpc.Channel; | |
import io.grpc.ClientCall; | |
import io.grpc.ClientInterceptor; | |
import io.grpc.ForwardingClientCall; | |
import io.grpc.Metadata; | |
import io.grpc.MethodDescriptor; | |
import io.grpc.Status; | |
import javax.annotation.Nullable; | |
/** | |
* Interceptor for tracing all client incoming and outgoing calls to SLF4J. | |
*/ | |
public class TracingClientInterceptor implements ClientInterceptor { | |
private static final Logger LOG = LoggerFactory.getLogger(TracingClientInterceptor.class); | |
@Override | |
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( | |
MethodDescriptor<ReqT, RespT> method, | |
CallOptions callOptions, | |
Channel next) { | |
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { | |
@Override | |
public void start(io.grpc.ClientCall.Listener<RespT> responseListener, Metadata headers) { | |
LOG.trace("start(headers={})", headers); | |
super.start(new ClientCall.Listener<RespT>() { | |
public void onHeaders(Metadata headers) { | |
LOG.trace("onHeaders(headers={})", headers); | |
responseListener.onHeaders(headers); | |
} | |
public void onMessage(RespT message) { | |
LOG.trace("onMessage()"); | |
responseListener.onMessage(message); | |
} | |
public void onClose(Status status, Metadata trailers) { | |
LOG.trace("onClose(status={} trailers={})", status, trailers); | |
responseListener.onClose(status, trailers); | |
} | |
public void onReady() { | |
LOG.trace("onReady()"); | |
responseListener.onReady(); | |
} | |
}, headers); | |
} | |
@Override | |
public void request(int numMessages) { | |
LOG.trace("request(numMessages={})", numMessages); | |
super.request(numMessages); | |
} | |
@Override | |
public void cancel(@Nullable String message, @Nullable Throwable cause) { | |
LOG.trace("cancel()"); | |
super.cancel(message, cause); | |
} | |
@Override | |
public void halfClose() { | |
LOG.trace("halfClose()"); | |
super.halfClose(); | |
} | |
@Override | |
public void sendMessage(ReqT message) { | |
LOG.trace("sendMessage()"); | |
super.sendMessage(message); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment