如何检查是否在REPL中评估Clojure代码?

我想根据我的代码是从REPL运行还是运行已编译的jar来格式化我的日志.

有没有简单的方法来做到这一点?我在想Leiningen在运行REPL时可能会留下痕迹.

最佳答案

(defn current-stack-trace []
      (.getStackTrace (Thread/currentThread)))

(defn is-repl-stack-element [stack-element]
      (and (= "clojure.main$repl" (.getClassName  stack-element))
           (= "doInvoke"          (.getMethodName stack-element))))

(defn is-in-repl []
      (some is-repl-stack-element (current-stack-trace)))

(defn my-log [msg]
      (if (is-in-repl)
          (prn (str "RUNNING IN REPL : " msg))
          (prn msg)))
点赞