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?
Clojure: log to console when code is being executed in a go block or thread
Asked Answered
send it to an agent who does the logging - If my theoretical knowledge is correct agents serialize their in-queu –
Relume
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)))
You could even
alts!
a separate channel instead of an atom for turning debugging on and off, and just make the on
/off
state a loop variable. –
Brachypterous 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).
There have been lots of standard Java logging frameworks over the years. They all need to be configured, have the right jar file in the right place, have incompatibilities between them ironed out, source code changes done (sometimes to every file). Which is the most likely to be the standard in the future - logback or log4j? –
Carburetor
Logback, although you'll use it through clojure.tools.logging "Logback is intended as a successor to the popular log4j project, picking up where log4j leaves off". My opinion on this is that it's worth taking the hour or so to learn a logging framework and it's config, as it will save you a lot of time in the long run. With slf4j and clojure.tools.logging, you can swap out the logging implementation and keep the same source. –
Oophorectomy
© 2022 - 2024 — McMap. All rights reserved.