Class: GrapeRailsLogger::GrapeRequestLogSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/grape_rails_logger/subscriber.rb,
sig/grape_rails_logger.rbs

Overview

Subscriber that logs Grape API requests with structured data

Automatically subscribed to "grape.request" notifications. Logs structured hash data compatible with JSON loggers.

This class is designed to be exception-safe: any error in logging is caught and logged separately, never breaking the request flow.

Defined Under Namespace

Classes: LoggingError

Constant Summary collapse

FILTERED_PARAMS =
%w[password secret token key].freeze
PARAM_EXCEPTIONS =
%w[controller action format].freeze

Instance Method Summary collapse

Constructor Details

#initializeGrapeRequestLogSubscriber

Returns a new instance of GrapeRequestLogSubscriber.



37
# File 'sig/grape_rails_logger.rbs', line 37

def initialize: () -> void

Instance Method Details

#grape_request(event) ⇒ void

This method returns an undefined value.

Parameters:

  • event (ActiveSupport::Notifications::Event)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/grape_rails_logger/subscriber.rb', line 23

def grape_request(event)
  return unless event.is_a?(ActiveSupport::Notifications::Event)

  env = event.payload[:env]
  return unless env.is_a?(Hash)

  # Get logger from event payload (passed from middleware)
  logger = event.payload[:logger]

  logged_successfully = false
  begin
    endpoint = env[Grape::Env::API_ENDPOINT] if env.is_a?(Hash)
    request = (endpoint&.respond_to?(:request) && endpoint.request) ? endpoint.request : nil

    data = build_log_data(event, request, env)
    logged_successfully = log_data(data, event.payload[:exception_object], logger)
    event.payload[:logged_successfully] = true if logged_successfully
  rescue LoggingError
    # If logging itself failed, don't try to log again (would cause infinite loop or duplicates)
    # The error was already logged in safe_log's rescue block
    # Silently skip to avoid duplicate logs
  rescue => e
    # Only call fallback if we haven't successfully logged yet
    # This prevents duplicate logs when logging succeeds but something else fails
    unless logged_successfully
      log_fallback_subscriber_error(event, e, logger)
    end
  end
end