Fork me on GitHub
#re-frame
<
2022-09-13
>
grahamcarlyle15:09:11

Does anyone do application level logging via fx? So dispatching logging events which create effects, which delegate to js/console or whatever. The lack of a built-in effect like this and that I couldn't find any such 3rd party libs suggests to me that not many people take this approach. The temporal gap between the site of the logging invocation to its eventual realisation seems a problem that such an approach would have despite logging technically being a side effect.

scarytom16:09:49

I work with graham, and I set up our re-frame application logging using fx, by creating a log namespace that looks roughly like this:

(rf/reg-fx
  ::record-log-message
  (fn [{:keys [env level message]}]
    (let [body (str (name env) "/" (name level) ": " message)]
      (case level
        ::info (js/console.info body)
        ::error (js/console.error body)
        (js/console.log body)))))

(defn- log-event-handler [{db :db} [level message]]
  {:fx [[::record-log-message {:env     (:environment db)
                               :level   level
                               :message message}]]})

(rf/reg-event-fx ::info log-event-handler)
(rf/reg-event-fx ::warn log-event-handler)
(rf/reg-event-fx ::error log-event-handler)

scarytom16:09:17

This allows us to log messages with something like (rf/dispatch [::log/error "oh dear"])

scarytom16:09:35

My thinking, as Graham suggests, was that logging is a side-effect, and hence should be handled in a re-frame effect. As Graham points out though, this does create a delay between logging a message and that message actually appearing in the console.

zalky21:09:13

When it comes to application logging (beyond what something like re-frame-10x provides) then the approach we use is to consider event processing and the animation frames as fundamentally different when it comes to serializability. On the event side, you log exclusively via returned fx (something like your ::record-log-message), which means a single log output that corresponds to all the processed effects for that event. No dispatching. During animation frames logging is much more rare, but if it happens, it is done directly via functions that log straight to console.

👍 2
zalky22:09:27

And just in case you haven't already looked at re-frame-10x, I highly encourage a peek. It's very powerful, but especially with more complex applications, I've found it works best when you build the application to play well with it from the start.

👍 1