Class: Lumberjack::Rails::RequestAttributesMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/lumberjack/rails/request_attributes_middleware.rb

Overview

This Rack middleware provides a hook for adding attributes from the request onto the Rails.logger context so that they will appear on all log entries for the request.

Instance Method Summary collapse

Constructor Details

#initialize(app, attributes_block) ⇒ RequestAttributesMiddleware

Returns a new instance of RequestAttributesMiddleware.

Parameters:

  • app (#call)

    The Rack application.

  • attributes_block (Proc)

    A block that takes the Rack request and returns a hash of attributes to add to the logger context for the request. The block will be called with an ActionDispatch::Request object.



13
14
15
16
17
18
19
20
# File 'lib/lumberjack/rails/request_attributes_middleware.rb', line 13

def initialize(app, attributes_block)
  unless attributes_block.respond_to?(:call)
    raise ArgumentError.new("attributes_block must be a Proc or callable object")
  end

  @app = app
  @attributes_block = attributes_block
end

Instance Method Details

#call(env) ⇒ Array

Process a request through the middleware stack with Lumberjack context.

Parameters:

  • env (Hash)

    the Rack environment hash

Returns:

  • (Array)

    the Rack response array



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/lumberjack/rails/request_attributes_middleware.rb', line 26

def call(env)
  return @app.call(env) if ::Rails.logger.nil?

  Lumberjack::Rails.logger_context do
    attributes = @attributes_block.call(ActionDispatch::Request.new(env))
    if attributes.is_a?(Hash)
      ::Rails.logger.tag(attributes)
    elsif !attributes.nil?
      warn "RequestAttributesMiddleware attributes_block did not return a Hash, got #{attributes.class.name}"
    end

    @app.call(env)
  end
end