Extend slacker server with interceptors

Sun 18 December 2011
  • 装备 tags:
  • clojure
  • github
  • project
  • slacker published: true comments: true

An interceptor framework was introduced in slacker 0.3.0. It's designed to allow user to add custom functionality without hacking into the internal of slacker.

Like many server frameworks, slacker abstracts the request processing as a pipeline. The request object is modified by adding or updating attributes through each node of the pipeline. So it's easy to add your interceptor into the pipeline, with which you can get the data before and after function executed.

To create such an interceptor, you should use the slacker.interceptor/definterceptor macro and slacker.interceptor/definterceptor+ macro:

(definterceptor name
:before interceptor-function
:after interceptor-function)

(definterceptor+ name [arguments]
:before interceptor-function
:after interceptor-function)

definterceptor+ can accept arguments so you can configure the interceptor when you use it.

See a simple example:
[cc lang="clojure"]
(definterceptor log-function-call
:before (fn [req] (println (str "calling " (:fname req))) req))

(definterceptor+ log-function-call-prefixed [prefix]
:before (fn [req] (println (str
(if (fn? prefix) (prefix) prefix)
" calling "
(:fname req)))
req))
[/cc]

Then, add it to your slacker server by
[cc lang="clojure"]
(use '[slacker.interceptor])
(import '[java.util Date])
(start-slacker (the-ns 'slapi) 2104
:interceptors (interceptors log-function-call
(log-function-call-prefixed
(fn [] (.toString (Date.)))))
[/cc]

Now you can log every function call of your slacker server.

For more detail about the interceptor framework, especially the request data, please check the wiki page.

In slacker 0.3.0, there is a built-in interceptor to stats function calls. You can find it at slacker.interceptors.stats. The stats data is expose via JMX. You can also write monitoring application to retrieve the data.

And there will be more built-in interceptors in 0.4.0, includes function call time stats and logging.