Clojure: log to console when code is being executed in a go block or thread

喜夏-厌秋 提交于 2019-12-12 00:20:01

问题


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?


回答1:


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)))



回答2:


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?



来源:https://stackoverflow.com/questions/32715869/clojure-log-to-console-when-code-is-being-executed-in-a-go-block-or-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!