Structured Logging in Rails You Can Actually Search

Structured Logging in Rails You Can Actually Search

At night when something is broken nobody wants to glue a request from pieces, so we took a small Rails 8.1 app, made one POST which fails with 422, and read what gets written in the log before lograge and after.

Without lograge the one request gave us several lines, Started, Processing, Completed, and with few processes writing together they get shuffled with the lines of other people. With lograge and JSON formatter it was exactly 1 line with method, path, status 422 and duration, and in custom_payload we added the request_id, which later becomes the most useful field.

# Gemfile
gem "lograge"
# config/environments/production.rb
config.lograge.enabled = true
config.lograge.formatter = Lograge::Formatters::Json.new
config.lograge.custom_payload do |controller|
  {
    request_id: controller.request.request_id,
    user_id: controller.try(:current_user)&.id,
    ip: controller.request.remote_ip
  }
end

Then comes the part where we felt stupid. We typed Rails.logger.info and put raw_post in it, only for test, and the log showed password=hunter2 as clear as day, while two lines up the same one was FILTERED, ha, filter knows only params. Same filter with our list did not touch card_number at all, and it hid footprint, because otp is inside, go figure.

# config/initializers/filter_parameter_logging.rb
Rails.application.config.filter_parameters += [
  :passw, :secret, :token, :_key, :otp, :ssn, :cvv
]

Jobs last. We put request_id in CurrentAttributes, serialize was reading it from Current, job we crashed two times by intention, and what we see, first run req-6c1f, second run nil, third nil, where did it go, so the retry is calling serialize one more time and Current is empty at that point, after we told serialize to ask the job before asking Current, we got our id on all three.

class Current < ActiveSupport::CurrentAttributes
  attribute :request_id
end

class ApplicationController < ActionController::Base
  before_action { Current.request_id = request.request_id }
end
class ApplicationJob < ActiveJob::Base
  attr_accessor :request_id

  def serialize
    super.merge("request_id" => request_id || Current.request_id)
  end

  def deserialize(job_data)
    super
    self.request_id = job_data["request_id"]
  end

  around_perform do |job, block|
    Current.set(request_id: job.request_id) do
      Rails.logger.tagged(job.request_id, &block)
    end
  end
end

See also: job debugging and webhooks.