Skip to content
Browse files

allow users to customize logs

  • Loading branch information...
1 parent 9c1e038 commit bf52d427fa2d121bca457f8458d73d42e2480ebf @schmurfy schmurfy committed Feb 12, 2012
Showing with 46 additions and 9 deletions.
  1. +21 −0 examples/custom_logs.rb
  2. +25 −9 lib/goliath/request.rb
View
21 examples/custom_logs.rb
@@ -0,0 +1,21 @@
+#!/usr/bin/env ruby
+$:<< '../lib' << 'lib'
+
+require 'goliath'
+
+Goliath::Request.log_block = proc do |env, response, elapsed_time|
+ method = env[Goliath::Request::REQUEST_METHOD]
+ path = env[Goliath::Request::REQUEST_PATH]
+
+ env[Goliath::Request::RACK_LOGGER].info("#{method} #{path} in #{'%.2f' % elapsed_time} ms")
+end
+
+class SimpleAPI < Goliath::API
+ def response(env)
+ [200, {}, "It worked !"]
+ end
+end
+
+# [19843:INFO] 2012-02-12 18:03:44 :: GET /some/url/ in 4.35 ms
+# [19843:INFO] 2012-02-12 18:03:49 :: GET /another/url/ in 4.24 ms
+# [19843:INFO] 2012-02-12 18:04:01 :: PUT /another/url/ in 4.16 ms
View
34 lib/goliath/request.rb
@@ -16,13 +16,18 @@ class Request
attr_accessor :app, :conn, :env, :response, :body
- ##
- # Allow user to redefine how fibers are handled, the
- # default is to spawn a new fiber each time but another
- # option is to use a pool of fibers.
- #
class << self
+ ##
+ # Allow user to redefine how fibers are handled, the
+ # default is to spawn a new fiber each time but another
+ # option is to use a pool of fibers.
+ #
attr_accessor :execute_block
+
+ ##
+ # Allow users to redefine what exactly is logged
+ #
+ attr_accessor :log_block
end
self.execute_block = proc do |&block|
@@ -184,10 +189,21 @@ def post_process(results)
begin
@response.status, @response.headers, @response.body = status, headers, body
@response.each { |chunk| @conn.send_data(chunk) }
-
- @env[RACK_LOGGER].info("Status: #{@response.status}, " +
- "Content-Length: #{@response.headers['Content-Length']}, " +
- "Response Time: #{"%.2f" % ((Time.now.to_f - @env[:start_time]) * 1000)}ms")
+
+ if Goliath::Request.log_block
+ elapsed_time = (Time.now.to_f - @env[:start_time]) * 1000
+ begin
+ Goliath::Request.log_block.call(@env, @response, elapsed_time)
+ rescue => err
+ # prevent an infinite loop if the block raised
+ @env[RACK_LOGGER].error("log block raised #{err}")
+ end
+
+ else
+ @env[RACK_LOGGER].info("Status: #{@response.status}, " +
+ "Content-Length: #{@response.headers['Content-Length']}, " +
+ "Response Time: #{"%.2f" % ((Time.now.to_f - @env[:start_time]) * 1000)}ms")
+ end
@conn.terminate_request(keep_alive)
rescue Exception => e

0 comments on commit bf52d42

Please sign in to comment.
Something went wrong with that request. Please try again.