Skip to content

Commit 7be099f

Browse files
committed
docs: fix tracing sample to exit when completed, and use custom monitored resource for export
1 parent b44104f commit 7be099f

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

samples/snippets/src/main/java/com/example/spanner/TracingSample.java

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,16 @@
1616

1717
package com.example.spanner;
1818

19+
import com.google.api.MonitoredResource;
20+
import com.google.cloud.MetadataConfig;
1921
import com.google.cloud.spanner.DatabaseClient;
2022
import com.google.cloud.spanner.DatabaseId;
2123
import com.google.cloud.spanner.ResultSet;
2224
import com.google.cloud.spanner.Spanner;
2325
import com.google.cloud.spanner.SpannerOptions;
2426
import com.google.cloud.spanner.Statement;
2527
import com.google.cloud.spanner.spi.v1.SpannerRpcViews;
28+
import io.opencensus.common.Duration;
2629
import io.opencensus.common.Scope;
2730
import io.opencensus.contrib.grpc.metrics.RpcViews;
2831
import io.opencensus.contrib.zpages.ZPageHandlers;
@@ -32,11 +35,12 @@
3235
import io.opencensus.trace.samplers.Samplers;
3336
import java.util.Arrays;
3437

35-
/** This sample demonstrates how to enable opencensus tracing and stats in cloud spanner client.
38+
/**
39+
* This sample demonstrates how to enable opencensus tracing and stats in cloud spanner client.
3640
*
37-
* @deprecated The OpenCensus project is deprecated. Use OpenTelemetry to enable metrics
38-
* and stats with cloud spanner client.
39-
*/
41+
* @deprecated The OpenCensus project is deprecated. Use OpenTelemetry to enable metrics and stats
42+
* with cloud spanner client.
43+
*/
4044
public class TracingSample {
4145

4246
private static final String SAMPLE_SPAN = "CloudSpannerSample";
@@ -58,7 +62,13 @@ public static void main(String[] args) throws Exception {
5862
.registerSpanNamesForCollection(Arrays.asList(SAMPLE_SPAN));
5963

6064
// Installs an exporter for stack driver stats.
61-
StackdriverStatsExporter.createAndRegister();
65+
MonitoredResource.Builder builder = MonitoredResource.newBuilder();
66+
if (MetadataConfig.getProjectId() != null) {
67+
builder.putLabels("project_id", options.getProjectId());
68+
}
69+
builder.setType("global");
70+
StackdriverStatsExporter.createAndRegisterWithProjectIdAndMonitoredResource(
71+
options.getProjectId(), Duration.create(60L, 0), builder.build());
6272
RpcViews.registerAllGrpcViews();
6373
// Capture GFE Latency and GFE Header missing count.
6474
SpannerRpcViews.registerGfeLatencyAndHeaderMissingCountViews();
@@ -87,6 +97,9 @@ public static void main(String[] args) throws Exception {
8797
} finally {
8898
// Closes the client which will free up the resources used
8999
spanner.close();
100+
StackdriverExporter.unregister();
101+
StackdriverStatsExporter.unregister();
102+
System.exit(0);
90103
}
91104
}
92105
}

0 commit comments

Comments
 (0)