Skip to content

Instantly share code, notes, and snippets.

@magnars
Created December 8, 2023 10:17
Show Gist options
  • Save magnars/849cdc6e0b6f0cc109f38c912ddc7144 to your computer and use it in GitHub Desktop.
Save magnars/849cdc6e0b6f0cc109f38c912ddc7144 to your computer and use it in GitHub Desktop.
Clojure macro: with-span
(def ^:dynamic *spans* nil)
(defn assoc-span [span-id & args]
(swap! *spans* #(for [span %]
(if (= (:id span) span-id)
(apply assoc span args)
span))))
(defmacro with-span [name details & body]
`(if *spans*
(let [start# (System/currentTimeMillis)
parent# (first (remove :duration @*spans*))
my-id# (random-uuid)
_# (swap! *spans* conj (cond-> {:name ~name
:id my-id#
:start-ms start#
:details ~details}
parent# (assoc :parent-id (:id parent#))))
res# (try
~@body
(catch Exception e#
(assoc-span my-id#
:error? true
:duration (- (System/currentTimeMillis) start#))
(throw e#)))]
(assoc-span my-id# :duration (- (System/currentTimeMillis) start#))
res#)
(do ~@body)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment