1212// See the License for the specific language governing permissions and
1313// limitations under the License.
1414
15+ #include < grpcpp/grpcpp.h>
16+ #include < grpcpp/opencensus.h>
17+
1518#include < cstdlib>
1619#include < iostream>
1720#include < memory>
1821#include < string>
1922
20- #include < grpcpp/grpcpp.h>
21- #include < grpcpp/opencensus.h>
22-
23+ #include " absl/strings/str_cat.h"
2324#include " absl/time/clock.h"
2425#include " examples/grpc/exporters.h"
2526#include " examples/grpc/hello.grpc.pb.h"
2627#include " examples/grpc/hello.pb.h"
28+ #include " opencensus/trace/context_util.h"
2729#include " opencensus/trace/sampler.h"
2830#include " opencensus/trace/trace_config.h"
31+ #include " opencensus/trace/with_span.h"
2932
3033namespace {
3134
@@ -51,17 +54,20 @@ int main(int argc, char **argv) {
5154
5255 RegisterExporters ();
5356
54- // Trace all outgoing RPCs.
55- opencensus::trace::TraceConfig::SetCurrentTraceParams (
56- {128 , 128 , 128 , 128 , opencensus::trace::ProbabilitySampler (1.0 )});
57-
5857 // Create a Channel to send RPCs over.
5958 std::shared_ptr<grpc::Channel> channel =
6059 grpc::CreateChannel (hostport, grpc::InsecureChannelCredentials ());
6160 std::unique_ptr<HelloService::Stub> stub = HelloService::NewStub (channel);
6261
63- // Send the RPC.
62+ // Create a span, this will be the parent of the RPC span.
63+ static opencensus::trace::AlwaysSampler sampler;
64+ auto span = opencensus::trace::Span::StartSpan (
65+ " HelloClient" , /* parent=*/ nullptr , {&sampler});
66+ std::cout << " HelloClient span context is " << span.context ().ToString ()
67+ << " \n " ;
6468 {
69+ opencensus::trace::WithSpan ws (span);
70+
6571 // The client Span ends when ctx falls out of scope.
6672 grpc::ClientContext ctx;
6773 ctx.AddMetadata (" key1" , " value1" );
@@ -70,12 +76,24 @@ int main(int argc, char **argv) {
7076 HelloReply reply;
7177 request.set_name (name);
7278 std::cout << " Sending request: \" " << request.ShortDebugString () << " \"\n " ;
79+ opencensus::trace::GetCurrentSpan ().AddAnnotation (" Sending request." );
7380
81+ // Send the RPC.
7482 grpc::Status status = stub->SayHello (&ctx, request, &reply);
7583
7684 std::cout << " Got status: " << status.error_code () << " : \" "
7785 << status.error_message () << " \"\n " ;
7886 std::cout << " Got reply: \" " << reply.ShortDebugString () << " \"\n " ;
87+ opencensus::trace::GetCurrentSpan ().AddAnnotation (
88+ " Got reply." , {{" status" , absl::StrCat (status.error_code (), " : " ,
89+ status.error_message ())}});
90+ if (!status.ok ()) {
91+ // TODO: Map grpc::StatusCode to trace::StatusCode.
92+ opencensus::trace::GetCurrentSpan ().SetStatus (
93+ opencensus::trace::StatusCode::UNKNOWN, status.error_message ());
94+ }
95+ // Don't forget to explicitly end the span!
96+ opencensus::trace::GetCurrentSpan ().End ();
7997 }
8098
8199 // Disable tracing any further RPCs (which will be sent by exporters).
0 commit comments