ruby 35 lines · 1 tab

API request logging for debugging and analytics

Alex Kumar Jan 2026
1 tab
module ApiRequestLogger
  extend ActiveSupport::Concern

  included do
    around_action :log_api_request
  end

  private

  def log_api_request
    start_time = Time.current

    yield

    duration = ((Time.current - start_time) * 1000).round(2)

    log_data = {
      request_id: request.request_id,
      method: request.method,
      path: request.path,
      params: filtered_params,
      status: response.status,
      duration_ms: duration,
      user_id: current_user&.id,
      ip: request.remote_ip,
      user_agent: request.user_agent
    }

    Rails.logger.info("API Request: #{log_data.to_json}")
  end

  def filtered_params
    params.except(:controller, :action, :password, :password_confirmation, :token).to_unsafe_h
  end
end
1 file · ruby Explain with highlit

Comprehensive request logging provides visibility into API usage patterns, performance bottlenecks, and security incidents. I log structured JSON that includes request method, path, parameters (sanitized to exclude passwords), response status, duration, and user context. For production systems, I send logs to a centralized aggregation service like Datadog or CloudWatch where I can query and alert on patterns. The key is balancing detail with noise—I avoid logging full request bodies for performance reasons, instead sampling them at low volume or in staging environments. Request IDs tie together all log entries for a single request, making distributed tracing possible without heavyweight instrumentation.


Related snips

Share this code

Here's the card — post it anywhere.

API request logging for debugging and analytics — share card
Link copied