Skip to content

Instantly share code, notes, and snippets.

@danneu
Last active December 16, 2015 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danneu/9cbed0c0743fe8011014 to your computer and use it in GitHub Desktop.
Save danneu/9cbed0c0743fe8011014 to your computer and use it in GitHub Desktop.
ring middleware that mimics rails server log output.
2013-Apr-11 01:57:00 INFO [hello-world.logger] - Started GET "/" for 127.0.0.1
2013-Apr-11 01:57:00 INFO [hello-world.logger] - Completed 200 OK in 1ms
2013-Apr-11 01:57:00 INFO [hello-world.logger] - Started GET "/brainsketch.gif" for 127.0.0.1
2013-Apr-11 01:57:00 INFO [hello-world.logger] - Completed 304 Not Modified in 4ms
(ns hello-world.logger
(:require [taoensso.timbre :refer [trace info debug warn error spy))
;; dependency: [com.taoensso/timbre "1.5.2"]
;; simple lookup table
(defn code->name
"Lookup table that maps http codes to a descriptive name."
[code]
(case code
200 "OK"
304 "Not Modified"
404 "File Not Found"
406 "Not Acceptable"
""))
;; a method that logs the
(defn log-request-started
"Log message based on first request that the middleware sees."
[request]
(let [{:keys [request-method uri remote-addr]} request
pp-method (upper-case request-method)
pp-uri (str "\"" uri "\"")]
(info "Started" pp-method pp-uri "for" remote-addr)))
(defn log-response-completed
"Log message based on the last response that middleware sees and an initial nanoTime start."
[response start]
(let [status-code (:status response)
status-name (code->name status-code)
duration (distance-ns->ms start (System/nanoTime))
pp-duration (str duration "ms")]
(info "Completed" status-code status-name "in" pp-duration)))
;; the actual middleware that incorporates the above
(defn wrap-railsy-logger
"Middleware that mimics Rails' dev server log output."
[handler]
(fn [request]
(log-request-started request)
(let [start (System/nanoTime)
response (handler request)]
(log-response-completed response start)
response)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment