The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Improve log context for exceptions (#55909)
John Swansonab8166e1cf9d
diff --git a/src/metabase/server/middleware/exceptions.clj b/src/metabase/server/middleware/exceptions.cljindex 7b84d4167d4..e1b4f0528fd 100644--- a/src/metabase/server/middleware/exceptions.clj+++ b/src/metabase/server/middleware/exceptions.clj@@ -22,7 +22,7 @@(defmethod api-exception-response Throwable[^Throwable e](let [{:keys [status-code], :as info} (ex-data e)- other-info (dissoc info :status-code :schema :type :toucan2/context-trace)+ other-info (dissoc info :status-code :schema :type :toucan2/context-trace ::log/context)body (cond(and status-code (not= status-code 500) (empty? other-info));; If status code was specified (but not a 500 -- an unexpected error, anddiff --git a/src/metabase/util/log.clj b/src/metabase/util/log.cljindex 172217b2fc6..6e141affbb4 100644--- a/src/metabase/util/log.clj+++ b/src/metabase/util/log.clj@@ -13,8 +13,26 @@[metabase.util.log.capture][net.cgrand.macrovich :as macros])(:import+ (clojure.lang ExceptionInfo)(org.apache.logging.log4j ThreadContext)))+(set! *warn-on-reflection* true)++(def ^:private suppressed-exception-context-message "METABASE HIDDEN EXCEPTION ONLY FOR CONTEXT")++(defn get-exception-data+ "Given an exception/throwable thrown by `with-exception-context-fn`, get the map of all context data contained in the+ suppressed exception(s) added. Inner context overrides outer context."+ [e]+ (let [ex-chain (->> e (iterate ex-cause) (take-while some?))+ suppressed-exception-data (->> ex-chain+ (mapcat (fn [^Throwable t]+ ;; reversed to make inner context override outer context+ (reverse (.getSuppressed t))))+ (keep #(when (= suppressed-exception-context-message (ex-message %))+ (::context (ex-data %)))))]+ (into {} suppressed-exception-data)))+;;; --------------------------------------------- CLJ-side macro helpers ---------------------------------------------(defn- glogi-logp"Macro helper for [[logp]] in CLJS."@@ -49,6 +67,41 @@(lambdaisland.glogi/log logger# level# nil s#)a#))))+(defn with-thread-context-fn+ "Not for public consumption. See macro docstring for details."+ [context-map f]+ (let [context-map (update-keys context-map #(str "mb-" (u.format/qualified-name %)))+ context-keys (keys context-map)+ ;; Store original values before modifying+ original-context (into {}+ (keep (fn [k]+ (when-let [v (ThreadContext/get (name k))]+ [(name k) v])))+ context-keys)]+ (try+ (doseq [k context-keys]+ (ThreadContext/put (name k) (str (get context-map k))))+ (f)+ (finally+ (doseq [k context-keys]+ (if-let [original (find original-context (name k))]+ (ThreadContext/put (name k) (val original))+ (ThreadContext/remove (name k))))))))++(defmacro with-thread-context+ "Executes body with the given context map and message prefix in ThreadContext.+ The context map's keys and values are added to the ThreadContext individually.+ Preserves any existing context values and restores them after execution.++ Example usage:+ (with-context {:notification_id 1}+ (log/infof \"Hello\"))++ ThreadContext will contain: {\"notification_id\" \"1\"} and stack \"Notification 1\""+ [context-map & body]+ `(with-thread-context-fn ~context-map+ (fn [] ~@body)))+(defn- tools-logp"Macro helper for [[logp]] in CLJ."[logger-ns level x more]@@ -56,9 +109,11 @@(when (clojure.tools.logging.impl/enabled? logger# ~level)(let [x# ~x](if (instance? Throwable x#)- (clojure.tools.logging/log* logger# ~level x# ~(if (nil? more)- ""- `(print-str ~@more)))+ (let [d# (get-exception-data x#)]+ (with-thread-context d#+ (clojure.tools.logging/log* logger# ~level x# ~(if (nil? more)+ ""+ `(print-str ~@more)))))(clojure.tools.logging/log* logger# ~level nil (print-str x# ~@more)))))))(defn- tools-logf@@ -211,6 +266,51 @@`(binding [clojure.tools.logging/*logger-factory* clojure.tools.logging.impl/disabled-logger-factory]~@body))+(defn- copy-ex-info+ "Copies an ExceptionInfo into a new ExceptionInfo with different ex-data & cause, but all other data the same"+ ^ExceptionInfo+ [^ExceptionInfo e new-data new-cause]+ (let [^ExceptionInfo new-e (ex-info (ex-message e) new-data new-cause)]+ (.setStackTrace new-e (.getStackTrace e))+ (doseq [^Throwable t (.getSuppressed e)]+ (.addSuppressed new-e t))+ new-e))++(defn- suppressed-exception+ [context-map]+ (ex-info suppressed-exception-context-message {::context context-map}))++(defn- annotate-ex-info [e context-map]+ (let [new-e (copy-ex-info e+ (assoc (ex-data e) ::context (merge {} context-map (::context (ex-data e))))+ (ex-cause e))]+ (.addSuppressed new-e (suppressed-exception context-map))+ new-e))++(defn- annotate-throwable [e context-map]+ (.addSuppressed ^Throwable e (suppressed-exception context-map))+ e)++(defn with-exception-context-fn+ "Not meant for public consumption.++ Runs `f`, catching any exceptions thrown and rethrowing them with:+ - `ex-data` augmented with `context-map`, only if the exception was an `ExceptionInfo`, and+ - a *suppressed* exception attached. The suppressed exception is meant purely to hold `ex-data` for later logging."+ [context-map f]+ (try+ (f)+ (catch ExceptionInfo e+ (throw (annotate-ex-info e context-map)))+ (catch Throwable e+ (throw (annotate-throwable e context-map)))))++(defmacro with-exception-context+ "Not meant for public consumption, use `with-context` instead."+ [context-map & body]+ `(with-exception-context-fn ~context-map+ (fn [] ~@body)))+(defmacro with-context"Executes body with the given context map and message prefix in ThreadContext.The context map's keys and values are added to the ThreadContext individually.@@ -220,24 +320,15 @@(with-context {:notification_id 1}(log/infof \"Hello\"))- ThreadContext will contain: {\"notification_id\" \"1\"} and stack \"Notification 1\""+ ThreadContext will contain: {\"notification_id\" \"1\"} and stack \"Notification 1\"++ Any exceptions thrown within the body will ALSO be annotated with the context (in a suppressed `ExceptionInfo`+ attached to the original exception, and/or directly in the `ex-data` if they're `ExceptionInfo`s already.++ If the exception is logged (via `log/error` or similar), the exception data attached above will be logged as well."[context-map & body](macros/case- :clj `(let [ctx-map# (update-keys ~context-map #(str "mb-" (u.format/qualified-name %)))- ctx-keys# (keys ctx-map#)- ;; Store original values before modifying- original-values# (into {}- (keep (fn [k#]- (when-let [v# (ThreadContext/get (name k#))]- [(name k#) v#])))- ctx-keys#)]- (try- (doseq [k# ctx-keys#]- (ThreadContext/put (name k#) (str (get ctx-map# k#))))- ~@body- (finally- (doseq [k# ctx-keys#]- (if-let [original# (find original-values# (name k#))]- (ThreadContext/put (name k#) (val original#))- (ThreadContext/remove (name k#)))))))+ :clj `(with-thread-context ~context-map+ (with-exception-context ~context-map+ ~@body)):cljs ~@body))diff --git a/test/metabase/driver/mysql_test.clj b/test/metabase/driver/mysql_test.cljindex 9b12b186168..f72bc239221 100644--- a/test/metabase/driver/mysql_test.clj+++ b/test/metabase/driver/mysql_test.clj@@ -694,30 +694,30 @@(sync/sync-database! database)(mt/with-actions-enabled(testing "when creating"- (is (= {:type :metabase.actions.error/violate-unique-constraint- :message "Column1 and Column2 already exist."- :errors {"column1" "This Column1 value already exists." "column2" "This Column2 value already exists."}- :status-code 400}- (sql-jdbc.actions-test/perform-action-ex-data- :model.row/create (mt/$ids {:create-row {"id" 3- "column1" "A"- "column2" "A"}- :database (:id database)- :query {:source-table $$mytable}- :type :query})))))+ (is (=? {:type :metabase.actions.error/violate-unique-constraint+ :message "Column1 and Column2 already exist."+ :errors {"column1" "This Column1 value already exists." "column2" "This Column2 value already exists."}+ :status-code 400}+ (sql-jdbc.actions-test/perform-action-ex-data+ :model.row/create (mt/$ids {:create-row {"id" 3+ "column1" "A"+ "column2" "A"}+ :database (:id database)+ :query {:source-table $$mytable}+ :type :query})))))(testing "when updating"- (is (= {:errors {"column1" "This Column1 value already exists."- "column2" "This Column2 value already exists."}- :message "Column1 and Column2 already exist."- :status-code 400- :type actions.error/violate-unique-constraint}- (sql-jdbc.actions-test/perform-action-ex-data- :model.row/update (mt/$ids {:update-row {"column1" "A"- "column2" "A"}- :database (:id database)- :query {:source-table $$mytable- :filter [:= $mytable.id 2]}- :type :query}))))))))))))+ (is (=? {:errors {"column1" "This Column1 value already exists."+ "column2" "This Column2 value already exists."}+ :message "Column1 and Column2 already exist."+ :status-code 400+ :type actions.error/violate-unique-constraint}+ (sql-jdbc.actions-test/perform-action-ex-data+ :model.row/update (mt/$ids {:update-row {"column1" "A"+ "column2" "A"}+ :database (:id database)+ :query {:source-table $$mytable+ :filter [:= $mytable.id 2]}+ :type :query}))))))))))))(deftest ^:parallel parse-grant-test(testing "`parse-grant` should work correctly"diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.cljindex 1f77148495c..c82ab330939 100644--- a/test/metabase/driver/postgres_test.clj+++ b/test/metabase/driver/postgres_test.clj@@ -1169,31 +1169,31 @@(sync/sync-database! database)(mt/with-actions-enabled(testing "when creating"- (is (= {:errors {"column1" "This Column1 value already exists."- "column2" "This Column2 value already exists."}- :message "Column1 and Column2 already exist."- :status-code 400- :type actions.error/violate-unique-constraint}- (sql-jdbc.actions-test/perform-action-ex-data- :model.row/create (mt/$ids {:create-row {"id" 3- "column1" "A"- "column2" "A"}- :database (:id database)- :query {:source-table $$mytable}- :type :query})))))+ (is (=? {:errors {"column1" "This Column1 value already exists."+ "column2" "This Column2 value already exists."}+ :message "Column1 and Column2 already exist."+ :status-code 400+ :type actions.error/violate-unique-constraint}+ (sql-jdbc.actions-test/perform-action-ex-data+ :model.row/create (mt/$ids {:create-row {"id" 3+ "column1" "A"+ "column2" "A"}+ :database (:id database)+ :query {:source-table $$mytable}+ :type :query})))))(testing "when updating"- (is (= {:errors {"column1" "This Column1 value already exists."- "column2" "This Column2 value already exists."}- :message "Column1 and Column2 already exist."- :status-code 400- :type actions.error/violate-unique-constraint}- (sql-jdbc.actions-test/perform-action-ex-data- :model.row/update (mt/$ids {:update-row {"column1" "A"- "column2" "A"}- :database (:id database)- :query {:source-table $$mytable- :filter [:= $mytable.id 2]}- :type :query}))))))))))))+ (is (=? {:errors {"column1" "This Column1 value already exists."+ "column2" "This Column2 value already exists."}+ :message "Column1 and Column2 already exist."+ :status-code 400+ :type actions.error/violate-unique-constraint}+ (sql-jdbc.actions-test/perform-action-ex-data+ :model.row/update (mt/$ids {:update-row {"column1" "A"+ "column2" "A"}+ :database (:id database)+ :query {:source-table $$mytable+ :filter [:= $mytable.id 2]}+ :type :query}))))))))))));;; ------------------------------------------------ Timezone-related ------------------------------------------------diff --git a/test/metabase/driver/sql_jdbc/actions_test.clj b/test/metabase/driver/sql_jdbc/actions_test.cljindex bfc40d870f5..30c2ebdca58 100644--- a/test/metabase/driver/sql_jdbc/actions_test.clj+++ b/test/metabase/driver/sql_jdbc/actions_test.clj@@ -108,73 +108,73 @@(test-action-error-handling!(fn [{:keys [db-id group-name]}](testing "violate not-null constraint"- (is (= {:message "Ranking must have values."- :errors {"ranking" "You must provide a value."}- :type actions.error/violate-not-null-constraint- :status-code 400}- (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "admin"}- :database db-id- :query {:source-table $$group}- :type :query}))))))))+ (is (=? {:message "Ranking must have values."+ :errors {"ranking" "You must provide a value."}+ :type actions.error/violate-not-null-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "admin"}+ :database db-id+ :query {:source-table $$group}+ :type :query}))))))))(deftest action-error-handling-not-null-constraint-creating-test-2(test-action-error-handling!(fn [{:keys [db-id group-name]}](testing "violate not-null constraint"(testing "when creating"- (is (= {:message "Ranking must have values."- :errors {"ranking" "You must provide a value."}- :type actions.error/violate-not-null-constraint- :status-code 400}- (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "admin"}- :database db-id- :query {:source-table $$group}- :type :query})))))))))+ (is (=? {:message "Ranking must have values."+ :errors {"ranking" "You must provide a value."}+ :type actions.error/violate-not-null-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "admin"}+ :database db-id+ :query {:source-table $$group}+ :type :query})))))))))(deftest action-error-handling-not-null-constraint-updating-test(test-action-error-handling!(fn [{:keys [db-id group-ranking]}](testing "violate not-null constraint"(testing "when updating"- (is (= {:message "Ranking must have values."- :errors {"ranking" "You must provide a value."}- :type actions.error/violate-not-null-constraint- :status-code 400}- (perform-action-ex-data :model.row/update (mt/$ids {:update-row {group-ranking nil}- :database db-id- :query {:filter [:= $group.id 1]- :source-table $$group}- :type :query})))))))))+ (is (=? {:message "Ranking must have values."+ :errors {"ranking" "You must provide a value."}+ :type actions.error/violate-not-null-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/update (mt/$ids {:update-row {group-ranking nil}+ :database db-id+ :query {:filter [:= $group.id 1]+ :source-table $$group}+ :type :query})))))))))(deftest action-error-handling-unique-constraint-creating-test(test-action-error-handling!(fn [{:keys [db-id group-name group-ranking]}](testing "violate unique constraint"(testing "when creating"- (is (= {:message "Ranking already exists."- :errors {"ranking" "This Ranking value already exists."}- :type actions.error/violate-unique-constraint- :status-code 400}- (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "new"- group-ranking 1}- :database db-id- :query {:source-table $$group}- :type :query})))))))))+ (is (=? {:message "Ranking already exists."+ :errors {"ranking" "This Ranking value already exists."}+ :type actions.error/violate-unique-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "new"+ group-ranking 1}+ :database db-id+ :query {:source-table $$group}+ :type :query})))))))))(deftest action-error-handling-unique-constraint-updating-test(test-action-error-handling!(fn [{:keys [db-id group-ranking]}](testing "violate unique constraint"(testing "when updating"- (is (= {:message "Ranking already exists."- :errors {"ranking" "This Ranking value already exists."}- :type actions.error/violate-unique-constraint- :status-code 400}- (perform-action-ex-data :model.row/update (mt/$ids {:update-row {group-ranking 2}- :database db-id- :query {:filter [:= $group.id 1]- :source-table $$group}- :type :query})))))))))+ (is (=? {:message "Ranking already exists."+ :errors {"ranking" "This Ranking value already exists."}+ :type actions.error/violate-unique-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/update (mt/$ids {:update-row {group-ranking 2}+ :database db-id+ :query {:filter [:= $group.id 1]+ :source-table $$group}+ :type :query})))))))))(defmethod driver/database-supports? [::driver/driver ::action-error-handling-incorrect-type-error-message][_driver _feature _database]@@ -190,84 +190,84 @@(fn [{:keys [db-id group-name group-ranking]}](testing "incorrect type"(testing "when creating"- (is (= {:message "Some of your values aren’t of the correct type for the database."- :type actions.error/incorrect-value-type- :status-code 400- :errors (if (driver/database-supports?- driver/*driver*- ::action-error-handling-incorrect-type-error-message- (mt/db))- {"ranking" "This value should be of type Integer."}- {})}- (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "new"- group-ranking "S"}- :database db-id- :query {:source-table $$group}- :type :query})))))))))+ (is (=? {:message "Some of your values aren’t of the correct type for the database."+ :type actions.error/incorrect-value-type+ :status-code 400+ :errors (if (driver/database-supports?+ driver/*driver*+ ::action-error-handling-incorrect-type-error-message+ (mt/db))+ {"ranking" "This value should be of type Integer."}+ {})}+ (perform-action-ex-data :model.row/create (mt/$ids {:create-row {group-name "new"+ group-ranking "S"}+ :database db-id+ :query {:source-table $$group}+ :type :query})))))))))(deftest action-error-handling-incorrect-type-updating-test(test-action-error-handling!(fn [{:keys [db-id group-ranking]}](testing "incorrect type"(testing "when updating"- (is (= {:message "Some of your values aren’t of the correct type for the database."- :type actions.error/incorrect-value-type- :status-code 400- :errors (if (driver/database-supports?- driver/*driver*- ::action-error-handling-incorrect-type-error-message- (mt/db))- {"ranking" "This value should be of type Integer."}- {})}- (perform-action-ex-data :model.row/update (mt/$ids {:update-row {group-ranking "S"}- :database db-id- :query {:filter [:= $group.id 1]- :source-table $$group}- :type :query})))))))))+ (is (=? {:message "Some of your values aren’t of the correct type for the database."+ :type actions.error/incorrect-value-type+ :status-code 400+ :errors (if (driver/database-supports?+ driver/*driver*+ ::action-error-handling-incorrect-type-error-message+ (mt/db))+ {"ranking" "This value should be of type Integer."}+ {})}+ (perform-action-ex-data :model.row/update (mt/$ids {:update-row {group-ranking "S"}+ :database db-id+ :query {:filter [:= $group.id 1]+ :source-table $$group}+ :type :query})))))))))(deftest action-error-handling-fk-constraint-creating-test(test-action-error-handling!(fn [{:keys [db-id user-name user-group-id]}](testing "violate fk constraint"(testing "when creating"- (is (= {:message "Unable to create a new record."- :errors {"group_id" "This Group-id does not exist."}- :type actions.error/violate-foreign-key-constraint- :status-code 400}- (perform-action-ex-data :model.row/create (mt/$ids {:create-row {user-name "new"- user-group-id 999}- :database db-id- :query {:source-table $$user}- :type :query})))))))))+ (is (=? {:message "Unable to create a new record."+ :errors {"group_id" "This Group-id does not exist."}+ :type actions.error/violate-foreign-key-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/create (mt/$ids {:create-row {user-name "new"+ user-group-id 999}+ :database db-id+ :query {:source-table $$user}+ :type :query})))))))))(deftest action-error-handling-fk-constraint-updating-test(test-action-error-handling!(fn [{:keys [db-id user-group-id]}](testing "violate fk constraint"(testing "when updating"- (is (= {:message "Unable to update the record."- :errors {"group_id" "This Group-id does not exist."}- :type actions.error/violate-foreign-key-constraint- :status-code 400}- (perform-action-ex-data :model.row/update (mt/$ids {:update-row {user-group-id 999}- :database db-id- :query {:filter [:= $user.id 1]- :source-table $$user}- :type :query})))))))))+ (is (=? {:message "Unable to update the record."+ :errors {"group_id" "This Group-id does not exist."}+ :type actions.error/violate-foreign-key-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/update (mt/$ids {:update-row {user-group-id 999}+ :database db-id+ :query {:filter [:= $user.id 1]+ :source-table $$user}+ :type :query})))))))))(deftest action-error-handling-fk-constraint-deleting-test(test-action-error-handling!(fn [{:keys [db-id]}](testing "violate fk constraint"(testing "when deleting"- (is (= {:message "Other tables rely on this row so it cannot be deleted."- :errors {}- :type actions.error/violate-foreign-key-constraint- :status-code 400}- (perform-action-ex-data :model.row/delete (mt/$ids {:database db-id- :query {:filter [:= $group.id 1]- :source-table $$group}- :type :query})))))))))+ (is (=? {:message "Other tables rely on this row so it cannot be deleted."+ :errors {}+ :type actions.error/violate-foreign-key-constraint+ :status-code 400}+ (perform-action-ex-data :model.row/delete (mt/$ids {:database db-id+ :query {:filter [:= $group.id 1]+ :source-table $$group}+ :type :query})))))))))(deftest actions-return-rows-with-correct-names-test(testing "rows returned by perform action should match the name in metabase_field.name"diff --git a/test/metabase/util/log_test.clj b/test/metabase/util/log_test.cljindex 0d3466e5b6f..322dbd9d3f5 100644--- a/test/metabase/util/log_test.clj+++ b/test/metabase/util/log_test.clj@@ -44,13 +44,34 @@(get-context))"Outer context should be restored after nested macro")))- (testing "with-context should reset context even if exception occurs"- (is (= original-context (get-context)))+ (try+ (log/with-context {:error "test"}+ (throw (Exception. "Test exception")))+ (catch Exception _))+ (is (empty? (get-context))+ "Context should be reset after exception")))- (try- (log/with-context {:error "test"}- (throw (Exception. "Test exception")))- (catch Exception _))-- (is (= original-context (get-context))- "Context should be reset after exception"))))+(deftest ^:parallel with-error-context-works+ (testing "has correct data for a basic example"+ (is (= {:foo "bar"}+ (log/get-exception-data+ (try (log/with-context {:foo "bar"}+ (/ 1 0))+ (catch Exception e+ e))))))+ (testing "nested: inner overrides outer"+ (is (= {:data "inner"}+ (log/get-exception-data+ (try (log/with-context {:data "outer"}+ (log/with-context {:data "inner"}+ (/ 1 0)))+ (catch Exception e e))))))+ (testing "a caught exception => context disappears"+ (is (= {:data "outer"}+ (log/get-exception-data+ (try (log/with-context {:data "outer"}+ (try (log/with-context {:data "inner"}+ (/ 1 0))+ (catch Exception _ nil))+ (/ 1 0))+ (catch Exception e e)))))))