Class: Lago::Api::LoggingRateLimitObserver

Inherits:
Object
  • Object
show all
Defined in:
lib/lago/api/logging_rate_limit_observer.rb

Overview

Ready-to-use on_rate_limit_info callable that logs a warning each time rate limit usage crosses one of the configured thresholds.

Example:

client = Lago::Api::Client.new(
  api_key: '...',
  on_rate_limit_info: Lago::Api::LoggingRateLimitObserver.new,
)

Constant Summary collapse

DEFAULT_THRESHOLDS =
[0.80, 0.90, 0.95].freeze

Instance Method Summary collapse

Constructor Details

#initialize(thresholds: DEFAULT_THRESHOLDS, logger: nil, level: Logger::WARN) ⇒ LoggingRateLimitObserver

Returns a new instance of LoggingRateLimitObserver.



18
19
20
21
22
# File 'lib/lago/api/logging_rate_limit_observer.rb', line 18

def initialize(thresholds: DEFAULT_THRESHOLDS, logger: nil, level: Logger::WARN)
  @thresholds = thresholds.sort.reverse
  @logger = logger || default_logger
  @level = level
end

Instance Method Details

#call(info) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/lago/api/logging_rate_limit_observer.rb', line 24

def call(info)
  pct = info.usage_pct
  return if pct.nil?

  return unless @thresholds.any? { |threshold| pct >= threshold }

  @logger.add(
    @level,
    format(
      'Lago rate limit at %<pct>.0f%% (limit=%<limit>s, remaining=%<remaining>s, ' \
      'reset=%<reset>ss, %<method>s %<url>s)',
      pct: pct * 100,
      limit: info.limit.inspect,
      remaining: info.remaining.inspect,
      reset: info.reset.inspect,
      method: info.method,
      url: info.url,
    ),
  )
end