Clojure: log to console when code is being execute

2019-08-31 03:42发布

With many go blocks going at once, all writing to the console, the text can get jumbled/intermingled when it arrives at the console. How to avoid this, so trace output forms as correctly in the console as intended when it was emitted from within the go block?

2条回答
forever°为你锁心
2楼-- · 2019-08-31 03:46

This answer uses core.async itself. The following from a talk:

;;;;; Logging Handler ;;;;;

(def log-chan (chan))

(thread
 (loop []
   (when-let [v (<!! log-chan)]
     (println v)
     (recur)))
 (println "Log Closed"))


(close! log-chan)

(defn log [msg]
  (>!! log-chan msg))

(log "foo")

Code copied verbatim from here

Talk was by Timothy Balridge and is here

I have an atom for turning debugging on and off. To be precise about the messages that are displayed the usage is like this:

(u/log @debug (str "Asked " info-ele ", and got back: " some-return))

At the other end like this:

(defn log [debug msg] 
  (when debug (>!! log-chan msg)))
查看更多
贼婆χ
3楼-- · 2019-08-31 04:05

Using a core.async channel to serialise all logging events will work, but a more standard way is to use a logging framework like logback or log4j. They are both designed for logging events from multiple threads (which is effectively what's happening when you're logging from inside a core.async go block).

Best practices for Java logging from multiple threads?

查看更多
登录 后发表回答