   f
   : function to invoke. track* returns the result from this function."
   [logger label f]
-  (if (bound? #'*operation-traces*)
+  (binding [*operation-traces* (conj *operation-traces* label)]
+    (set-should-log-operations! true)
     (try
-      (swap! *operation-traces* conj label)
-      (when *log-traces* (l/log* logger :trace nil (label-to-string label)))
+      (when *log-trace-level*
+        (l/log* logger *log-trace-level* nil (label-to-string label)))
       (f)
       (catch Throwable e
-        (if @*innermost-exception*
-          (let [trace-label-strings (mapv label-to-string @*operation-traces*)
+        (if (should-log-operations?)
+          (let [trace-label-strings (mapv label-to-string *operation-traces*)
                 message (or (.getMessage e) (-> e .getClass .getName))]
-            (log-trace-label-stack logger trace-label-strings message e)
-            (reset! *innermost-exception* false)
+            (log-trace-label-stack logger trace-label-strings e)
+            (set-should-log-operations! false)
             (throw (ex-info message
                             {:operation-trace trace-label-strings}
                             e)))
-          (throw e)))
-      (finally
-        (swap! *operation-traces* pop)))
-    ;; Else, if not yet bound..
-    (binding [*operation-traces* (atom [])
-              *innermost-exception* (atom true)]
-      (track* logger label f))))
+          (throw e))))))
 
 (defn get-logger
   "Determines the logger instance for a namespace (by leveraging some clojure.tools.logging internals)."

(ns io.aviso.tracker
  "Code for tracking operations so that a history can be presented when an exception is thrown."
  (:require
    [clojure.tools.logging :as l]
    [clojure.tools.logging.impl :as impl]
    [io.aviso.exception :as exception]))

;;; Contains a vector of messages (or functions that return messages) used to log the route to the exception.
(def ^:dynamic ^:private *operation-traces*)

(def ^:dynamic ^:private *innermost-exception*)

(def ^:dynamic *log-traces*
  "A boolean to control the whether traces are logged at :trace level as they are created."
  false)

(defn- label-to-string
  "Converts a trace to a string; a trace may be a function which is invoked."

(defn- error [logger message]
  (l/log* logger :error nil message))

(defn- log-trace-label-stack [logger trace-labels e]
  (let [lines (concat ["An exception has occurred."]
                      (map-indexed (fn [i label]
                                     (format "[%3d] - %s" (inc i) label))
                                   trace-labels)
                      [(exception/format-exception e)])]
    (->> lines
         (str/join writer/eol)
         (error logger))))

(defn track*
  "Tracks the execution of a function of no arguments. The trace macro converts into a call to track*.
