2013-06-26 2 views
10

저는 Clojure를 사용하고 있으며 로그 할 수있는 스택 추적을하고 싶습니다 (이상적으로는 String으로 가져오고 싶습니다).stacktrace를 문자열로 얻으십시오.

나는 (.getStackTrace e)StackTraceElement[]을 반환한다고보고 있지만 의미있는 것을 인쇄하는 방법을 모르겠습니다. 내 두 번째 접근 방식은 PrintWriter를 매개 변수로 사용하여 (.printStackTrace e) (Java에서 가능하다는 것을 알고 있기 때문에)이지만 올바른 구문을 얻지 못하는 것 같습니다.

감사합니다.

답변

16

number23_cn의 솔루션은 조금 더 있다면, 이것은 당신이 다음 인쇄 할 수있는 (문자열로 .getStackTrace의 결과를 사용할 수있는 방법입니다 , 로그에 무엇이든 넣으십시오)

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

사용 clojure.repl.pst는 스택 트레이스를 얻고, *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

작품을 사용할 수 있습니다. 그냥 내가 첫 번째 문장을 변경하는 걸 썼다. ([clojure.repl : only (pst)] 사용) – sebi

5

여기 noisesmith의 답변에 비해 약간의 개선이 있습니다. 그것은 게으른 서열을 떠나 미화 기능이되지 않습니다

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

또한 print-stack-trace, print-trace-element 및 일부 기타 유용한 기능을 가지고 clojure.stacktrace이 있습니다.

0

당신은 마법처럼 with-out-str

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