noziar
noziar

Reputation: 1057

How to check whether Clojure code is being evaluated inside a REPL?

I would like to format my logs differently depending on whether my code is being run from a REPL or if I'm running the compiled jar.

Is there any simple way to do this? I was thinking maybe Leiningen leaves a trace somewhere when running the REPL.

Upvotes: 6

Views: 414

Answers (1)

Alfred Xiao
Alfred Xiao

Reputation: 1788

(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)))

Upvotes: 4

Related Questions