Clojure: Debugging Println, __LINE_NUMBER__ and __FILE_NAME__

Context

Currently

(println "x is" x)

just prints

x is 10

Now I want something like this:

(my-println "x is" x)

for print:

foo.clj:23> x is 10

Informally, I want my-println to add _FILE_NAME_ and _LINE_NUMBER_ to my println.

Question:

I know how to use macros. However, I do not know how to extract _FILE_NAME_ and _LINE_NUMBER_ from the current location in Clojure (whereas C macros do this trivially). How to get the current FILE_NAME_ and _LINE_NUMBER_ files?

Thank.

+5
source share
2 answers
(defmacro my-println [x]
  `(do (printf "%s:%s> %s is %s\n"
               ~*file*
               ~(:line (meta &form))
               ~(pr-str x)
               ~x)
       (flush)))

Looking at this answer again much later, you can be a little smarter if you like, reducing the cost of runtime by interpolating string constants at compile time:

(defmacro my-println [x]
  `(println ~(format "%s:%s> %s is"
                     *file*
                     (:line (meta &form))
                     (pr-str x))
            ~x))

, printf :

(let [x 5] (macroexpand '(my-println (+ x 5))))
(clojure.core/println "foo.clj:1> (+ x 5) is" (+ x 5))
+10

Java, log4j logback ​​. , . , , , .

clojure.logging, .

0

All Articles