2013-06-26 18 views
10

Sto usando Clojure e voglio mettere le mani su una traccia di stack che posso registrare (idealmente, mi piacerebbe averlo come una stringa).Ottieni stacktrace come stringa

Vedo che (.getStackTrace e) restituisce un StackTraceElement[] ma non so come stampare qualcosa di significativo da esso. Il mio secondo approccio è stato (.printStackTrace e) con un PrintWriter come parametro (perché so che è possibile in Java), ma non sembra che ottenga la sintassi corretta.

Grazie.

risposta

16

se la soluzione di number23_cn è un po 'troppo, questo è come è possibile utilizzare il risultato di .getStackTrace come stringa (che possono poi essere stampato , inserisci un log, qualunque sia)

(try (/ 1 0) 
    (catch Throwable t 
    (map str (.getStackTrace t)))) 
8

uso clojure.repl.pst ottenere StackTrace, e vincolante *err*-java.io.StringWriter:

(use '[clojure.repl :only (pst)]) 

(defmacro with-err-str 
    "Evaluates exprs in a context in which *err* is bound to a fresh 
    StringWriter. Returns the string created by any nested printing 
    calls." 
    [& body] 
    `(let [s# (new java.io.StringWriter)] 
    (binding [*err* s#] 
     [email protected] 
     (str s#)))) 

(try 
    (/ 1 0) 
    (catch Exception e 
    (let [s (with-err-str (pst e 36))] 
     (println "Error log:") 
     (println s)))) 
+0

funziona come un fascino. Solo che mi piacerebbe cambiare la prima istruzione in (usa [clojure.repl: only (pst)])) – sebi

5

Ecco un leggero miglioramento rispetto alla risposta di rumori del fabbro. Non lascia un ss pigro e ha una caratteristica abbellimento:

(apply str (interpose "\n" (.getStackTrace t))) 
0

C'è anche clojure.stacktrace che ha print-stack-trace, print-trace-element e alcune altre funzioni utili.

0

è possibile utilizzare with-out-str

(try 
    (name nil) 
    (catch Exception e 
    (with-out-str (println e))))