Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created July 3, 2012 17:15
Show Gist options
  • Save martintrojer/3041119 to your computer and use it in GitHub Desktop.
Save martintrojer/3041119 to your computer and use it in GitHub Desktop.
logging
(let [id (java.util.UUID/randomUUID)]
(emit-timed {:id id :op :add})
(emit-timed {:id id :cat :backend :op :send})
(emit-timed {:id id :cat :backend :op :ack :parent-op :send})
(emit-timed {:id id :cat :backend :op :sub :parent-op :send})
(emit-timed {:id id :cat :distribution :op :contribute})
(emit-timed {:id id :cat :distribution :op :chain-contribute})
(emit-timed {:id id :cat :distribution :op :chain-event :parent-op :contribute})
(emit-timed {:id id :op :done :parent-op :add})))
(def log (agent {}))
(defn- add-log [id data time & corr-ids]
(send log #(let [keys (into [id] corr-ids)
log-node (get-in % keys {:entries []})
entries (:entries log-node)]
(assoc-in % keys
(assoc log-node :entries
(conj entries {:time time
:data data}))))))
(defn emit
"Emit data to the log, with a given id and potential corr-ids"
[id data & corr-ids]
(apply add-log id data (System/nanoTime) corr-ids))
(def log (agent []))
(defn emit
"Emit data to the log"
[data]
(send log #(conj % data)))
(defn emit-timed
"Emit datas to the log, timestamp appended"
[data]
(emit (assoc data :time (System/nanoTime))))
(defn get-ids
"Return a set of ids seen in the log"
[log]
(->> log
(map :id)
set))
(defn get-log
"Get chronological logs for a given id"
[log id]
(->> log
(filter #(= (:id %) id))
(sort-by :time)))
(defn get-ids
"Get all ids in log"
[log]
(keys log))
(defn- walk-nodes [node f path]
(when node
(f node path)
(doseq [child-id (filter #(not= % :entries) (keys node))]
(walk-nodes (get node child-id) f (conj path child-id)))))
(defn get-log
"Get all log entries for a given id in chronological oder"
[log id]
(let [evts (atom [])]
(walk-nodes (get log id)
(fn [n _] (swap! evts #(into % (:entries n))))
[id])
(->> evts (sort-by :time) (map :data))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment