Spanspan= tracer.spanBuilder("my span").startSpan(); try (Scopescope= tracer.withSpan(span)) { // your use case ... } catch (Throwable t) { Statusstatus= Status.UNKNOWN.withDescription("Change it to your error message"); span.setStatus(status); } finally { span.end(); // closing the scope does not end the span, this has to be done manually }
// Tell OpenTelemetry to inject the context in the HTTP headers HttpTextFormat.Setter<HttpURLConnection> setter = newHttpTextFormat.Setter<HttpURLConnection>() { @Override publicvoidput(HttpURLConnection carrier, String key, String value) { // Insert the context as Header carrier.setRequestProperty(key, value); } };
URLurl=newURL("http://127.0.0.1:8080/resource"); SpanoutGoing= tracer.spanBuilder("/resource").setSpanKind(Span.Kind.CLIENT).startSpan(); try (Scopescope= tracer.withSpan(outGoing)) { // Semantic Convention. // (Observe that to set these, Span does not *need* to be the current instance.) outGoing.setAttribute("http.method", "GET"); outGoing.setAttribute("http.url", url.toString()); HttpURLConnectiontransportLayer= (HttpURLConnection) url.openConnection(); // Inject the request with the *current* Context, which contains our current Span. OpenTelemetry.getPropagators().getHttpTextFormat().inject(Context.current(), transportLayer, setter); // Make outgoing call } finally { outGoing.end(); } ...
// Gets or creates a named meter instance Metermeter= OpenTelemetry.getMeter("instrumentation-library-name","semver:1.0.0");
// Build counter e.g. LongCounter LongCountercounter= meter .longCounterBuilder("processed_jobs") .setDescription("Processed jobs") .setUnit("1") .build();
// It is recommended that the API user keep a reference to a Bound Counter for the entire time or // call unbind when no-longer needed. BoundLongCountersomeWorkCounter= counter.bind("Key", "SomeWork");
// Record data someWorkCounter.add(123);
// Alternatively, the user can use the unbounded counter and explicitly // specify the labels set at call-time: counter.add(123, "Key", "SomeWork");
Observer是支持异步API并按需收集度量数据的附加工具,按间隔收集数据。
以下是观察者用法的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Build observer e.g. LongObserver LongObserverobserver= meter .observerLongBuilder("cpu_usage") .setDescription("CPU Usage") .setUnit("ms") .build();