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

1

6

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.

Juice answered 23/5, 2015 at 5:9 Comment(0)
D
4
(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)))
Diastyle answered 23/5, 2015 at 13:38 Comment(3)
Nice trick! I was looking for some kind of variable stored somewhere, but I guess the stack does the job just fine :)Juice
You might want to memoize that, could be expensive.Morman
This will only work with code actually executed in the REPL after start-up. While the REPL is starting up and pre-loading your namepsaces, that function isn't in the stack tracePredict

© 2022 - 2024 — McMap. All rights reserved.