Skip to content

Commit

Permalink
ひとまずそれっぽいやつを書いてみたが、時間ないのでまだ動かしていない
Browse files Browse the repository at this point in the history
  • Loading branch information
walf443 committed May 9, 2012
1 parent f10e484 commit 92b709d
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Gemfile
Expand Up @@ -5,6 +5,10 @@ source "http://rubygems.org"

# Add dependencies to develop your gem here.
# Include everything needed to run rake, tests, features, etc.
#
gem 'fluent-logger'
gem 'rack'

group :development do
gem "rspec", "~> 2.8.0"
gem "rdoc", "~> 3.12"
Expand Down
2 changes: 2 additions & 0 deletions lib/rack-common_logger-fluent.rb
@@ -0,0 +1,2 @@
# just alias.
require 'rack/common_logger/fluent'
68 changes: 68 additions & 0 deletions lib/rack/common_logger/fluent.rb
@@ -0,0 +1,68 @@
require 'fluent-logger'

module Rack
class CommonLogger
#
# @example
# # in your config.ru
#
# require 'fluent-logger'
# require 'rack/common_logger/fluent'
#
# logger = Fluent::Logger::FluentLogger.new(nil, :host => 'localhost', :port => 24224)
# use Rack::CommonLogger::Fluent, 'myapp', logger
#
# # if you want to customize format
# use Rack::CommonLogger::Fluent, 'myapp', logger do |info|
# result = {}
#
# # ...
#
# result
# end
#
class Fluent
def initialize(app, tag, logger=nil, &format)
@app = app
@logger = logger || Fluent::Logger::FluentLogger.new(nil, :host => 'localhost', :port => 24224)
@tag = tag
@format = format || lambda do |info|
hash = {}

hash["remote_addr"] = info[:env]["HTTP_X_FORWARDED_FOR"] || info[:env]["REMOTE_ADDR"] || '-'
hash["accessed_at"] = info[:now].strftime('%d/%b/%Y %H:%M:%S')
hash["request_method"] = info[:env]["REQUEST_METHOD"]
hash["path_info"] = info[:env]["PATH_INFO"]
hash["query_string"] = info[:env]["QUERY_STRING"].empty? ? "" : '?' + info[:env]["QUERY_STRING"]
hash["http_version"] = info[:env]["HTTP_VERSION"]
hash["http_status"] = info[:status].to_s[0..3]
hash["content_length"] = info[:length]
hash["runtime"] = info[:runtime]

hash
end
end

def call(env)
began_at = Time.now
status, header, body = @app.call(env)
header = Utils::HeaderHash.new(header)
body = BodyProxy.new(body) { log(env, status, header, began_at) }
[status, header, body]
end

def log(env, status, header, began_at)
now = Time.now
length = extract_content_length(header)
result = @format.call({ :env => env, :status => status, :header => header, :now => now, :runtime => now - began_at, :length => length })
@logger.post(result)
end

def extract_content_length(headers)
value = headers['Content-Length'] or return '-'
value.to_s == '0' ? '-' : value
end
end
end
end

0 comments on commit 92b709d

Please sign in to comment.