-
Notifications
You must be signed in to change notification settings - Fork 2
/
otel.clj
57 lines (49 loc) · 1.83 KB
/
otel.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
(ns otel.otel
(:import [io.opentelemetry.api GlobalOpenTelemetry]
[io.opentelemetry.api.trace Span SpanKind Tracer]
[io.opentelemetry.context Context]))
(defn ^Tracer tracer
"Set up a tracer using the OpenTelemetry API"
[]
(let [tracer-provider (GlobalOpenTelemetry/getTracerProvider)]
(.get tracer-provider "otel.otel clojure")))
(def span-kinds
{:internal SpanKind/INTERNAL
:server SpanKind/SERVER
:client SpanKind/CLIENT
:producer SpanKind/PRODUCER
:consumer SpanKind/CONSUMER})
(def default-opts
{:kind :internal})
(defn ^Span current-span [] (Span/current))
(defn ^Span span
"Create a span. The optional `opts` can set various properties on the span,
and when not provided uses `default-opts`."
([span-name]
(span span-name default-opts))
([span-name opts]
(let [{:keys [kind link-spans attributes]} (merge default-opts opts)
builder (->
(.spanBuilder (tracer) span-name)
(.setSpanKind (span-kinds kind))
(.setAttribute "thread.id" (.getId (Thread/currentThread)))
(.setAttribute "thread.name" (.getName (Thread/currentThread))))]
(when (seq attributes)
(doall (map (fn [[k v]] (.setAttribute builder k v)) attributes)))
(when (seq link-spans)
(.setParent builder (current-span))
(doall (map (fn [^Span s] (.addLink builder (.getSpanContext s))) link-spans)))
(.startSpan builder))))
(defn span-scope
"Open a Scope for a Span, to be used with with-open"
[span]
(.makeCurrent (.with (Context/current) span)))
(defmacro with-span
[span-binding & body]
(let [[span-sym span-args] span-binding]
`(let [span-args# ~span-args
~span-sym (apply span span-args#)]
(try
(with-open [_# (span-scope ~span-sym)]
~@body)
(finally (.end ~span-sym))))))