Skip to content

Instantly share code, notes, and snippets.

@RickMoynihan
Created March 18, 2021 10:26
Show Gist options
  • Save RickMoynihan/8714a86f7f1f30b22136597305e50ca4 to your computer and use it in GitHub Desktop.
Save RickMoynihan/8714a86f7f1f30b22136597305e50ca4 to your computer and use it in GitHub Desktop.
Clojure macro to capture log4j2 ThreadContexts
;; Originally dual licensed under EPL 1.0 and AGPL 3.
(import 'org.apache.logging.log4j.ThreadContext)
(defn capture-logging-context []
(into {} (ThreadContext/getContext)))
;; Modified from withdrawn library:
;; https://github.com/malcolmsparks/clj-logging-config/blob/master/src/main/clojure/clj_logging_config/log4j.clj
(defmacro with-logging-context [x & body]
`(let [x# ~x
ctx# (capture-logging-context)]
(try
(if (map? x#)
(run! (fn [[k# v#]]
(when-not (nil? v#)
(ThreadContext/put (name k#) (str v#)))) x#)
(ThreadContext/push (str x#)))
~@body
(finally
(if (map? x#)
(run! (fn [[k# v#]]
(ThreadContext/remove (name k#))
(when-let [old# (get ctx# (name k#))]
(ThreadContext/put (name k#) (str old#)))) x#)
(ThreadContext/pop))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment