clojure:向命名空间中的每个函数添加调试跟踪? [英] clojure: adding a debug trace to every function in a namespace?

查看:11
本文介绍了clojure:向命名空间中的每个函数添加调试跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始在我的一个家庭项目中使用 log4j,我正要打开鼠标并剪切和粘贴 (trace (str "entering: " function-name))进入一个大模块中的每个函数.然后理性的声音赶上并说必须有更好的方法"......我可以考虑制作一个宏来包装整个功能块并为它们添加跟踪或类似的东西?明智的 Stack-overflowing-clojurians 有什么建议吗?

just started using log4j in one of my home-projects and I was just about to break out the mouse and cut-and-paste (trace (str "entering: " function-name)) into every function in a large module. then the voice of reason caught up and said "there has simply got to be a better way"... I can think of making a macro that wraps a whole block of functions and adds the traces to them or something like that? Any advice from the wise Stack-overflowing-clojurians?

推荐答案

不需要宏:

(defn trace-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))]
    (intern ns
            (with-meta s {:traced true :untraced @v})
            (let [f @v] (fn [& args]
                          (clojure.contrib.trace/trace (str "entering: " s))
                          (apply f args))))))

(defn untrace-ns [ns]
  (doseq [s (keys (ns-interns ns))
          :let [v (ns-resolve ns s)]
          :when (:traced (meta v))]
    (alter-meta! (intern ns s (:untraced (meta v)))
                 #(dissoc % :traced :untraced))))

...或类似的东西.最可能的额外要求是使用 filter 以免对不是 ifn? 的事物调用 trace.更新:在解决方案中编辑(也处理宏).更新 2:修复了一些主要错误.更新 4:添加了 untrace 功能.

...or something similar. The most likely extra requirement would be to use filter so as not to call trace on things which aren't ifn?s. Update: edited in a solution to that (also handling macros). Update 2: fixed some major bugs. Update 4: added untrace functionality.

更新 3: 这是我的 REPL 中的一个示例:

Update 3: Here's an example from my REPL:

user> (ns foo)
nil
foo> (defn foo [x] x)
#'foo/foo
foo> (defmacro bar [x] x)
#'foo/bar
foo> (ns user)
nil
user> (trace-ns 'foo)
nil
user> (foo/foo :foo)
TRACE: "entering: foo"
:foo
user> (foo/bar :foo)
:foo
user> (untrace-ns 'foo)
nil
user> (foo/foo :foo)
:foo

这篇关于clojure:向命名空间中的每个函数添加调试跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆