Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compojure support #13

Closed
devurandom opened this issue Nov 23, 2023 · 2 comments
Closed

Compojure support #13

devurandom opened this issue Nov 23, 2023 · 2 comments

Comments

@devurandom
Copy link

The following middleware adds route information to spans when using Compojure:

(ns steffan-westcott.clj-otel.api.trace.http
  (:require
   [compojure.core :as compojure]))

(defn wrap-compojure-route
  "Ring middleware to add matched Compojure route to the server span and Ring
   request map."
  [handler]
  (compojure/wrap-routes handler (fn [route-handler]
                                   (trace-http/wrap-route route-handler (comp second :compojure/route)))))

It can be used in the same way as steffan-westcott.clj-otel.api.trace.http/wrap-reitit-route.

To avoid adding a dependency on Compojure for projects that do not use it, some optional-require mechanism would be needed. I don't know how people commonly do that, but the following seems to work:

(ns steffan-westcott.clj-otel.api.trace.http)

(def wrap-compojure-route
  "Ring middleware to add matched Compojure route to the server span and Ring
   request map."
  (try
    (when-let [compojure-core-wrap-routes (requiring-resolve 'compojure.core/wrap-routes)]
      (fn [handler]
        (compojure-core-wrap-routes handler (fn [route-handler]
                                              (trace-http/wrap-route route-handler (comp second :compojure/route))))))
    ;; `requiring-resolve` throws `java.io.FileNotFoundException` when the namespace cannot be required:
    (catch Exception _)))
@devurandom
Copy link
Author

devurandom commented Dec 12, 2023

The above code does not capture the full route if compojure/route is used: weavejester/compojure#192 (comment)

The following code works:

(defn- extract-compojure-route
  [{:compojure/keys [route route-context]}]
  (str route-context (second route)))

(defn- wrap-compojure-route
  "Ring middleware to add matched Compojure route to the server span and Ring
   request map."
  [handler]
  (compojure/wrap-routes handler (fn [route-handler]
                                   (trace-http/wrap-route route-handler extract-compojure-route))))

@steffan-westcott
Copy link
Owner

@devurandom Thank you for your help. Building on your insight, I've added support for Compojure route data and an example showing its use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants