class Sawmill::LogRecordMiddleware

A Rack middleware that starts and ends a log record. Insert this in your Rack stack to wrap requests in a log record.

Public Class Methods

new(app_, logger_=nil, opts_={}) click to toggle source

Create a middleware object for Rack.

If you do not provide a logger object, one will be generated for you that simply logs to STDOUT.

Recognized options include:

:request_id_key

The name of a rack environment key where the request ID should be stored. If not specified, defaults to “sawmill.request_id”.

:start_time_attribute

If present, logs an attribute with this name with the starting timestamp for the request. If absent, does not log this attribute.

:end_time_attribute

If present, logs an attribute with this name with the ending timestamp for the request. If absent, does not log this attribute.

:elapsed_time_attribute

If present, logs an attribute with this name with the elapsed time for the request, in seconds. If absent, does not log this attribute.

:pre_logger

A proc that is called at the start of the request, and passed the logger and the rack environment. Optional.

:post_logger

A proc that is called at the end of the request, and passed the logger and the rack environment. Optional.

# File lib/sawmill/log_record_middleware.rb, line 72
def initialize(app_, logger_=nil, opts_={})
  @app = app_
  @logger = logger_ || Logger.new(:progname => 'rack', :processor => Formatter.new(::STDOUT))
  @request_id_key = opts_[:request_id_key] || 'sawmill.request_id'
  @start_time_attribute = opts_[:start_time_attribute]
  @end_time_attribute = opts_[:end_time_attribute]
  @elapsed_time_attribute = opts_[:elapsed_time_attribute]
  @pre_logger = opts_[:pre_logger]
  @post_logger = opts_[:post_logger]
end

Public Instance Methods

call(env_) click to toggle source
# File lib/sawmill/log_record_middleware.rb, line 84
def call(env_)
  env_[@request_id_key] = @logger.begin_record
  start_time_ = ::Time.now.utc
  if @start_time_attribute
    @logger.set_attribute(@start_time_attribute, start_time_.strftime('%Y-%m-%dT%H:%M:%S.') + ('%06d' % start_time_.usec) + 'Z')
  end
  if @pre_logger
    @pre_logger.call(@logger, env_)
  end
  begin
    return @app.call(env_)
  ensure
    if @post_logger
      @post_logger.call(@logger, env_)
    end
    end_time_ = ::Time.now.utc
    if @end_time_attribute
      @logger.set_attribute(@end_time_attribute, end_time_.strftime('%Y-%m-%dT%H:%M:%S.') + ('%06d' % end_time_.usec) + 'Z')
    end
    if @elapsed_time_attribute
      @logger.set_attribute(@elapsed_time_attribute, '%.6f' % (end_time_ - start_time_))
    end
    @logger.end_record
  end
end