skip to content

In a Rails 8.1 production app, how do config.log_tags and ActiveSupport::TaggedLogging let you pull every log line of one slow checkout?

level: middleimportance: should knowfreq 38%

answer

  1. [:request_id] in generated production.rb
  2. Rails::Rack::Logger pushes tags per request
  3. symbol, proc or plain value
  4. X-Request-Id in and out
  5. Rails.logger.tagged in your own code

basics

~20 s

Production sets log_tags = [:request_id] on a TaggedLogging logger, so every line of a request starts with that request's id. Search for one id, for example from the X-Request-Id response header, and you get every line of one checkout.

solid answer

~40 s

The generated production.rb sets `config.log_tags = [ :request_id ]` and `config.logger = ActiveSupport::TaggedLogging.logger(STDOUT)`. For each request, the `Rails::Rack::Logger` middleware computes the tags and pushes them onto the logger before it writes `Started`, and pops them when the response body closes. A symbol is called as a method on the `ActionDispatch::Request`, a proc is called with the request, and anything else is used as is. `ActionDispatch::RequestId` keeps a client's `X-Request-Id` (sanitised, at most 255 characters) or generates a UUID, and echoes it in the response header. So one id from a support ticket or the browser's network tab finds every line. For facts known only later, such as the signed-in user, wrap code in `Rails.logger.tagged(...)`.

code

ruby · 9 lines
ruby
# config/environments/production.rb (Rails 8.1)
config.log_tags = [
  :request_id,
  ->(request) { request.headers["X-Store-Region"] || "eu" }
]
config.logger = ActiveSupport::TaggedLogging.logger(STDOUT)

# Resulting line:
# [8d0f6a3e-...] [eu] Completed 302 Found in 2104ms (ActiveRecord: 1950.2ms (38 queries, 4 cached) | GC: 3.1ms)

go deeper

for a junior

Recall that production tags every line with the request id and that one id finds every line of a request.

for a middle

Explain how Rails::Rack::Logger computes symbol, proc and literal tags, where the request id comes from, and why it is echoed in X-Request-Id.

for a senior

Show how you would link a slow checkout's request, its jobs and the customer, knowing what log_tags can and cannot see in middleware.

for a principal

Decide which identifiers every service in the estate must propagate and log, and how Rails' request id fits that convention.

## Why tags exist Puma serves several requests at once on threads, so their log lines interleave in one stream. In a busy electronics store, the lines of one slow checkout sit among dozens of product-page hits. **Tagged logging** prefixes each line with bracketed context, such as `[f3c1...]`, so one search returns one request's lines in order. ## How the pieces fit 1. **The logger.** `ActiveSupport::TaggedLogging` wraps a standard logger so that its formatter prepends the current tags. `TaggedLogging.logger(STDOUT)` builds an `ActiveSupport::Logger` and wraps it in one call. That is what the generated `production.rb` uses. 2. **The configuration.** `config.log_tags` is a list. For each entry, `Rails::Rack::Logger#compute_tags` decides: - a **Symbol** is sent to the request: `:request_id` calls `request.request_id`, `:remote_ip` calls `request.remote_ip`, `:subdomain` calls `request.subdomain`; - a **Proc** is called with the `ActionDispatch::Request`; - **anything else**, such as a string, is used as is. 3. **The middleware.** `Rails::Rack::Logger` pushes the computed tags before it logs `Started`, then wraps the response body so the tags are popped when the body closes. Every line logged in between carries them: Action Controller's, Active Record's, and your own `Rails.logger.info` calls. 4. **The id.** `ActionDispatch::RequestId` runs earlier in the stack. If the request carries `X-Request-Id`, from a proxy or another service, it keeps that value with characters other than word characters, `-` and `@` removed, cut to 255. Otherwise it generates `SecureRandom.uuid`. It always writes the id back into the response's `X-Request-Id` header. ```ruby # config/environments/production.rb config.log_tags = [ :request_id, ->(request) { request.headers["X-Store-Region"] || "eu" } ] config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) ``` ## Tracing one slow checkout A customer reports a checkout that hung. The browser's network tab or your edge logs show the response's `X-Request-Id`. A search for that id returns `Started`, `Processing by CheckoutsController#create`, any app lines, and `Completed ... in 2104ms`, all from one request. Then you can read the timing breakdown without guessing which lines belong together. ## Choosing tags Every tag is computed on every request and printed on every line, so the list deserves the same care as any hot path: - **`:request_id`** is the one to keep. Rails generates it, returns it to the client and stamps every line with it. - **`:remote_ip`** is useful behind trusted proxies, but it is personal data in many jurisdictions and repeats on every line. - **`:subdomain`** helps a multi-tenant store that serves each region or brand from its own subdomain. - **Procs** should only read what is already on the request, such as a header. A proc that queries the database runs once per request, before the controller, and its cost lands on every page. - **Literal strings**, such as a release name, are set once at boot and are often better handled by the log pipeline than by every line. ## What log_tags cannot see, and what to do instead `Rails::Rack::Logger` sits in the middleware stack **before** the cookie and session middleware, the router and the controller. So a `log_tags` proc runs before `Current.user` is set and before the session is loaded. Tagging lines with the signed-in customer belongs in the controller: ```ruby class ApplicationController < ActionController::Base around_action :tag_logs_with_customer private def tag_logs_with_customer Rails.logger.tagged("customer:#{Current.user&.id || "guest"}") { yield } end end ``` The `Started` and `Processing by` lines come before this callback, so they do not carry the customer tag. Lines from inside the action do. `Rails.logger.tagged` has two forms. With a block, it pushes the tags for the block's duration. Without one, it returns a new logger that always carries them, for example `log = Rails.logger.tagged("payment")`. ## Jobs and other boundaries - **Active Job** tags a job's own lines with `[ActiveJob] [JobClassName] [job_id]`. The request id does **not** follow the job to the worker. To connect them, log the job id on the request side when you enqueue. - **Tags are text.** Each tag is turned into a string, so keep them short and free of secrets. They repeat on every line. - **Tags live in the formatter.** The tag stack belongs to the tagged formatter, so an extra log sink with its own default formatter prints lines without the brackets. ## Takeaway `log_tags` is evaluated per request, in middleware, from the request object alone. The request id is the one tag worth having everywhere, because Rails generates it, echoes it to the client and stamps every line with it. Context known only later goes in through `Rails.logger.tagged`.

  • Why can't a log_tags proc read Current.user to tag lines with the customer id?
    `Rails::Rack::Logger` runs in the middleware stack before the session middleware, the router and the controller. When the proc runs, no `before_action` has authenticated anyone, so `Current.user` is still nil. Add the customer tag from the controller with an `around_action` that wraps the action in `Rails.logger.tagged("customer:#{Current.user&.id}") { yield }`.
  • A load balancer already sets X-Request-Id. Will Rails use it or generate its own?
    It uses it. `ActionDispatch::RequestId` reads the configured header, `X-Request-Id` by default via `config.action_dispatch.request_id_header`. It strips characters other than word characters, `-` and `@`, truncates to 255, and only generates a UUID when the header is blank. The same value goes into the log tag and back out in the response header, so balancer and app logs share one id.
  • Does a job enqueued during the checkout log under the request's id?
    No. Active Job tags its lines with `[ActiveJob]`, the job class and the job's own id, and the worker has no request. To connect the two, log the job id in the request, for example from the job instance `perform_later` returns, or pass the request id to the job and tag with it there.

A hospital stamps the patient's case number on every sheet that goes into the shared tray, so all of one patient's sheets can be pulled out later. The stamp goes on at admission, before anyone knows the diagnosis, so anything learned later has to be written on the sheet itself.

  • log_tags symbols are looked up in the params hash of the request.
  • A log_tags proc can tag lines with Current.user because it runs per request.
  • Rails ignores a client's X-Request-Id and always generates a fresh UUID.
  • Tags pushed by Rails::Rack::Logger also appear on the request's background job lines.
  • Rails.logger.tagged without a block raises, because tags need a block to pop.