How to Add Amazon Trace IDs in Rails with Lograge and Doorkeeper
So, AWS adds a super useful X-Amzn-Trace-Id
header to http requests behind a ALB. You want it. It’s the bare minimum for tracing across multiple services.
But, it’s totally not obvious how to cleanly get the header into a Rails request log entry, and doubly not obvious on how to do that with Doorkeeper.
The solution is simple, but non trivial. I’ll explain.
# frozen_string_literal: true
# config/initializers/lograge.rb
Rails.application.configure do
config.lograge.formatter = Lograge::Formatters::Json.new
config.lograge.base_controller_class = [
"ActionController::API",
"ActionController::Base",
"Doorkeeper::ApplicationsController"
]
config.lograge.custom_payload do |controller|
{
trace_id: controller.request.headers["HTTP_X_AMZN_TRACE_ID"]
}
end
end
You’ll need the lograge gem to your app. It makes adding extra fields to the log entries easy. It also turns your request logs into something more structured for Cloudwatch to ingest and parse. It’s very nice.
Also not obvious, Doorkeeper controllers inherit from Doorkeeper::ApplicationsController
, not ActionController::Base
which is why all your non Doorkeeper controller actions automagically get the trace_id
in the logs, but Doorkeeper actions don’t.
But once you let lograge know about Doorkeeper’s controller class, everything becomes nice and magical again.
Running Rails on AWS? Reach out and say hi 👋🏽!