-
Notifications
You must be signed in to change notification settings - Fork 0
/
logging.clj
56 lines (52 loc) · 2.26 KB
/
logging.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
(ns capn-hook.logging
"Logging utilities that include performance logging. Parts pulled from
Guaranteed-Rate/logdog open source project."
(:require [clojure.tools.logging :refer [log logf logp]]
[robert.hooke :refer [add-hook]]))
(defn now [] (System/currentTimeMillis))
(defn execution-time-logging-hook
"Given a config map, returns a hook function that logs execution time."
[{:keys [level func-name msg msg-fn ns] :or {level :info}}]
(let [labeler (fn [msg]
(str func-name (if msg (str " [" msg "]"))))
logf (fn [s & args]
(log ns level nil (apply format s args)))]
(fn [func & args]
(let [start (now)]
(try
(let [ret (apply func args)
time-taken (- (now) start)
label (labeler
(cond msg msg
msg-fn (try (apply msg-fn ret args)
(catch Throwable t (str "msg-fn error! " t)))
:else nil))]
(logf "Finished %s in %dms." label time-taken)
ret)
(catch Throwable t
(let [time-taken (- (now) start)]
(logf "Error in %s after %dms (%s)." (labeler nil) time-taken (.getMessage t)))
(throw t)))))))
(defmacro log-execution-time!
"A macro for adding execution time logging to a named
function. Simply call at the top level with the name of the function
you want to wrap. As a second argument you may provide an options
map with possible values:
{
:level ;; defaults to :info
:msg ;; some string that is printed with the log messages
:msg-fn ;; a function that will be called with the return value
;; and the arguments, and should return a message for
;; inclusion in the log
}"
([var-name] `(log-execution-time! ~var-name {}))
([var-name opts]
`(add-hook (var ~var-name)
::execution-time
(execution-time-logging-hook
(assoc ~opts
:func-name '~var-name
;; pass in the namespace so the log messages
;; can have the appropriate namespace instead
;; of ns-toolkit.logging
:ns ~*ns*)))))