ruby
35 lines · 1 tab
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
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
ruby
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
rails
hotwire
turbo
by codesnips
4 tabs
ruby
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
rails
activerecord
patterns
by Alex Kumar
1 tab
ruby
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
rails
caching
http-caching
by Alex Kumar
1 tab
ruby
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
rails
turbo
hotwire
by codesnips
4 tabs
ruby
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
rails
performance
streaming
by codesnips
3 tabs
Share this code
Here's the card — post it anywhere.