Skip to content

Commit

Permalink
[#251 #292] spit-appender: add locking for thread safety
Browse files Browse the repository at this point in the history
  • Loading branch information
ptaoussanis committed Sep 13, 2020
1 parent 865d6cd commit d531880
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions src/taoensso/timbre/appenders/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,24 @@
#?(:clj
(defn spit-appender
"Returns a simple `spit` file appender for Clojure."
[& [{:keys [fname append?]
[& [{:keys [fname append? locking?]
:or {fname "./timbre-spit.log"
append? true}}]]
append? true
locking? true}}]]

{:enabled? true
:async? true ; For thread safety, see #251
:async? false
:min-level nil
:rate-limit nil
:output-fn :inherit
:fn
(let [system-newline enc/system-newline]
(let [lock (Object.) ; For thread safety, Ref. #251
system-newline enc/system-newline]

(fn self [data]
(let [{:keys [output_]} data]
(try
(when locking? (monitor-enter lock))
(with-open [^java.io.BufferedWriter w (jio/writer fname :append? append?)]
(.write w ^String (force output_))
(.newLine w))
Expand All @@ -96,7 +101,11 @@
dir (.getParentFile (.getCanonicalFile file))]

(when-not (.exists dir) (.mkdirs dir))
(self (assoc data :spit-appender/retry? true)))))))))}))
(self (assoc data :spit-appender/retry? true)))))

(finally
(when locking?
(monitor-exit lock)))))))}))

(comment
(spit-appender)
Expand Down

0 comments on commit d531880

Please sign in to comment.