Fork me on GitHub
#pedestal
<
2022-03-11
>
jmv19:03:17

hey all, what's the best way to set the *mdc-context* so that the value is reflect in every interceptor in the chain? basically i would like to set some metadata at the start of a request, so that logging in the rest of the interceptors in the chain have this metadata.

jmv19:03:39

also, if setting *mdc-context* is not the best way to do this, lemme know!

ghadi19:03:54

Not sure about that particular dynvar, but if an interceptor returns a context with :bindings , they will be active through further interceptors http://pedestal.io/reference/context-map

jmv20:03:00

thank you for sharing! this sounds like exactly what i'm looking for

Phillip Mates14:05:26

I'm also trying to manipulate the *mdc-context* via an interceptor, in order to set a correlation-id per request. I tried binding *mdc-context* to something using pedestal's :bindings but found it wasn't enough to actually get the new context to register. After some debugging I realized that one still needs to "install" the new context in the MDC. I'm thinking something like this will do the trick:

{:name ::cid
 :enter (fn [context]
          (let [new-mdc-context (merge .... io.pedestal.log/*mdc-context*)]
            (io.pedestal.log/-put-mdc (MDC/getMDCAdapter)
                                 io.pedestal.log/mdc-context-key
                                 (pr-str (dissoc new-mdc-context
                                                 :io.pedestal.log/formatter
                                                 :io.pedestal.log/mdc)))
          (-> context
              (update context
                      :bindings
                      assoc
                      #'io.pedestal.log/*mdc-context*
                      new-mdc-context)
              (assoc ::old-mdc-context io.pedestal.log/*mdc-context*))))
 :leave (fn [context]
          (when-let [old-mdc-context (::old-mdc-context context)]
            ;; go back to old MDC
            (io.pedestal.log/-put-mdc (MDC/getMDCAdapter)
                                   io.pedestal.log/mdc-context-key
                                   (pr-str (dissoc old-mdc-context
                                                   :io.pedestal.log/formatter
                                                   :io.pedestal.log/mdc))))
          context)}
wanted to share if that helps others with similar issue

gratitude-thank-you 2