Module: LambdaLoadout::Middleware

Defined in:
lib/lambda_loadout/middleware.rb

Overview

Middleware for Ruby Lambda handlers

Provides a clean way to wrap Lambda handlers with logging, metrics, and error handling without repetitive boilerplate code.

Examples:

Using as a wrapper

class MyHandler
  include LambdaLoadout::Middleware

  def initialize
    @logger = LambdaLoadout::Logger.new(service: "payment")
    @metrics = LambdaLoadout::Metrics.new(namespace: "MyApp", service: "payment")
  end

  def call(event:, context:)
    with_observability(context) do
      @logger.info("Processing payment", event: event)
      @metrics.add_metric(name: "PaymentProcessed", unit: "Count", value: 1)

      { statusCode: 200, body: "Success" }
    end
  end
end

Instance Method Summary collapse

Instance Method Details

#with_observability(context, capture_cold_start: true, logger: nil, metrics: nil) { ... } ⇒ Object

Execute block with full observability stack

Automatically:

  • Injects Lambda context into logger

  • Captures cold start metric

  • Flushes metrics after execution

  • Handles errors with proper logging and metrics

Parameters:

  • context (Object)

    Lambda context

  • capture_cold_start (Boolean) (defaults to: true)

    Whether to capture cold start

  • logger (LambdaLoadout::Logger) (defaults to: nil)

    Logger instance (uses @logger if not provided)

  • metrics (LambdaLoadout::Metrics) (defaults to: nil)

    Metrics instance (uses @metrics if not provided)

Yields:

  • Block containing handler logic

Returns:

  • (Object)

    Result of block execution



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/lambda_loadout/middleware.rb', line 42

def with_observability(context, capture_cold_start: true, logger: nil, metrics: nil, &block)
  logger ||= @logger
  metrics ||= @metrics

  logger&.inject_lambda_context(context)

  begin
    result = block.call
    metrics&.add_cold_start_metric(context) if capture_cold_start
    result
  rescue StandardError => e
    logger&.exception(e, message: 'Lambda execution failed')
    metrics&.add_metric(name: 'LambdaError', unit: 'Count', value: 1)
    raise
  ensure
    begin
      metrics&.flush
    rescue StandardError
      nil
    end
  end
end