Class: RightSupport::Rack::RequestLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/right_support/rack/request_logger.rb

Overview

A Rack middleware that logs information about every HTTP request received and every exception raised while processing a request.

The middleware can be configured to use its own logger, but defaults to using env for logging if it is present. If ‘rack.logger’ is not set, this middleware will set it before calling the next middleware. Therefore, RequestLogger can be used standalone to fulfill all logging needs, or combined with Rack::Logger or another middleware that provides logging services.

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ RequestLogger

Initialize an instance of the middleware.

Parameters:

  • app (Object)

    inner application or middleware layer; must respond to #call

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :only (Array)

    log for these path Regexps unless in debug mode

  • :except (Array)

    log except for these path Regexps unless in debug mode



43
44
45
46
47
# File 'lib/right_support/rack/request_logger.rb', line 43

def initialize(app, options = {})
  @app = app
  @only = options[:only]
  @except = options[:except]
end

Instance Method Details

#call(env) ⇒ Object

Add a logger to the Rack environment and call the next middleware. Set “rack.logging.enabled” in Rack environment to indicate whether logging is enabled for this request for use by other middleware in the call chain.

Parameters:

  • env (Hash)

    Rack environment

Returns:

  • (Object)

    always returns whatever value is returned by the next layer of middleware



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/right_support/rack/request_logger.rb', line 56

def call(env)
  logger = env["rack.logger"]
  env["rack.logging.enabled"] = enabled = logging_enabled?(logger, env)

  began_at = Time.now

  log_request_begin(logger, env) if enabled
  status, header, body = @app.call(env)
  log_exception(logger, env['sinatra.error']) if env['sinatra.error']
  log_request_end(logger, status, header, began_at) if enabled

  return [status, header, body]
rescue Exception => e
  log_exception(logger, e)
  raise
end