Search code examples
loggingclojurenamespaces

Get callers namespace in clojure


I wrapped a logging library in Clojure; Let's call the namespace of this foo.logger. Now I have another namespace like bar.baz and from there I call the logger.

Is there some idiomatic/nice way, that I can determine the namespace of the callers namespace inside the logger? I don't want to set this as parameter for the logger ;-)


Solution

  • This is one of those rare cases where using a macro is a solid choice.

    Making that a macro that prints the value of *ns will get the value of *ns* in the callers space because the macro will expand and run in that namespace.

    (defmacro log [msg]
      `(printf "%s:%s\n" ~*ns* ~msg))
    

    Try to be aware of "macro contagion" around this because anything that wants to extend this function will need to also be a macro, though I have been doing this for the last six years and it hasn't been a problem often.