Skip to content

Instantly share code, notes, and snippets.

@dcj
Created February 16, 2012 18:52
Show Gist options
  • Save dcj/1846993 to your computer and use it in GitHub Desktop.
Save dcj/1846993 to your computer and use it in GitHub Desktop.
My take on tracing
(ns testtrace
(:use clojure.tools.trace
clojure.contrib.pprint))
(defn trace-fn
([fun-sym] (trace-fn *ns* fun-sym))
([ns fun-sym]
(let [sym (if (symbol? fun-sym)
fun-sym
(:name (meta fun-sym)))
fvar (ns-resolve ns sym)]
(alter-var-root fvar
(fn [traced-fun]
(let [new-fun (partial trace-fn-call fvar traced-fun)]
(with-meta #(new-fun [%])
(assoc (meta @fvar)
:traced traced-fun))))))))
(defn untrace-fn
([fun-sym] (untrace-fn *ns* fun-sym))
([ns fun-sym]
(let [sym (if (symbol? fun-sym)
fun-sym
(:name (meta fun-sym)))
fvar (ns-resolve ns sym)]
(alter-meta! (intern ns sym (:traced (meta @fvar)))
dissoc :traced))))
(defn trace-ns
"Replaces each function from the given namespace with a version wrapped
in a tracing call. Can be undone with untrace-ns. ns should be a namespace
object or a symbol."
[ns]
(doseq [s (keys (ns-interns ns))
:let [v (ns-resolve ns s)]
:when (and (ifn? @v) (-> v meta :macro not))]
(trace-fn ns s)))
(defn untrace-ns
"Reverses the effect of trace-ns, replacing each traced function from the
given namespace with the original, untraced version."
[ns]
(doseq [s (keys (ns-interns ns))
:let [v (ns-resolve ns s)]
:when (:traced (meta v))]
(untrace-fn ns s)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment