Created
February 16, 2017 23:18
-
-
Save noisesmith/473508b96380729255e82910d28eb913 to your computer and use it in GitHub Desktop.
attach debugging info to a var, detach cleanly later
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn set-debug | |
[target-var] | |
(let [metadata (meta target-var) | |
target (::original metadata @target-var) | |
debug-data (:debug-trace metadata (atom []))] | |
;; only one layer of debugging, if we were already debugging, | |
;; just replace the previous layer | |
(when-not (and (:debug-trace metadata) | |
(::original metadata)) | |
(alter-meta! target-var assoc | |
::original target | |
:debug-trace debug-data)) | |
(alter-var-root | |
target-var | |
(constantly | |
(fn replaced-debugging-function | |
[& args] | |
(let [result (try (apply target args) | |
(catch Exception e | |
{::error e}))] | |
(swap! debug-data conj {:at (java.util.Date.) | |
:args args | |
:result result}) | |
(if-let [error (::error result)] | |
(throw error) | |
result))))))) | |
(defn unset-debug | |
[target-var] | |
(let [metadata (meta target-var) | |
debug-data (:debug-trace metadata)] | |
(when-let [original (::original metadata)] | |
(alter-meta! target-var dissoc ::original :debug-trace) | |
(alter-var-root target-var (constantly original))) | |
@debug-data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment