I'm thinking of something like this:
(defn my-function []
(println "entered" *current-function*)
...
)
--
R. Mark Volkmann
Object Computing, Inc.
> Is there a special variable that holds the name of the currently
> running function so it can be output in a logging message?
>
> I'm thinking of something like this:
>
> (defn my-function []
> (println "entered" *current-function*)
> ...
> )
Maintaining such a var by updating its value on every function entry
would be prohibitively expensive in runtime in the general case.
As e mentioned, it's possible to use the exception system to get the
name of the current function in a particular case.
Here's an example:
[debug_utils.clj]
(ns debug-utils
(:use [clojure.contrib.str-utils :only (re-sub)]))
(defn unmangle
"Given the name of a class that implements a Clojure function,
returns
the function's name in Clojure"
[class-name]
(re-sub #"^(.+)\$(.+)__\d+$" "$1/$2" class-name))
(defmacro current-function-name []
"Returns a string, the name of the current Clojure function"
`(-> (Throwable.) .getStackTrace first .getClassName unmangle))
[repl]
Clojure 1.0.0-RC1-SNAPSHOT
user=> (use 'debug-utils)
nil
user=> (defn my-cool-func []
(println "entered" (current-function-name))
5)
#'user/my-cool-func
user=> (my-cool-func)
entered user/my_cool_func
5
user=>
--Steve
> #'user/my-cool-func
> user=> (my-cool-func)
> entered user/my_cool_func
> 5
But my_cool_func isn't my-cool-func...
Corrected code in "unmangle" in case anybody wants to use it sometime:
(ns debug-utils
(:use [clojure.contrib.str-utils :only (re-sub)]))
(defn unmangle
"Given the name of a class that implements a Clojure function,
returns
the function's name in Clojure. Note: If the true Clojure function
name
contains any underscores (a rare occurrence), the unmangled name will
contain hyphens at those locations instead."
[class-name]
(.replace
(re-sub #"^(.+)\$(.+)__\d+$" "$1/$2" class-name)
\_ \-))
(defmacro current-function-name []
"Returns a string, the name of the current Clojure function"
`(-> (Throwable.) .getStackTrace first .getClassName unmangle))
[repl]
Clojure 1.0.0-RC1-SNAPSHOT
user=> (use 'debug-utils)
nil
user=> (defn my-cool-func []
(println "entered" (current-function-name))
5)
#'user/my-cool-func
user=> (my-cool-func)
entered user/my-cool-func
5
user=>
--Steve