In Rails, how do you add a custom query log tag such as the current school's id, and when does its lambda receive a context?
answer
- a Hash inside the query_log_tags array
- one-argument lambda gets the context
- :controller, :job and :connection keys
- zero-argument lambda reads Current
- nil value: the tag is dropped
basics
~20 sAdd a Hash to config.active_record.query_log_tags, such as { school_id: -> { Current.school&.id } }. A one-parameter lambda receives a context hash with the controller, job and connection; a zero-parameter lambda is just called. Nil drops the tag.
solid answer
~40 s`config.active_record.query_log_tags` is an array of symbols and hashes. Each hash entry adds a tag whose value can be a static string, a one-argument lambda or a zero-argument lambda. `ActiveRecord::QueryLogs` inspects the lambda's arity: with one parameter it is called with a context hash that holds `:controller` (the controller instance during an action), `:job` (the job instance during `perform`) and `:connection`, so `->(context) { context[:controller]&.request&.request_id }` adds the request id. With no parameters it is just called, which suits `-> { Current.school&.id }`. A nil result omits the tag, values are escaped so they cannot close the comment, and untrusted input should still stay out. Rails keeps adding `:controller`, `:action` and `:job` itself unless you turn those off. `:source_location` exists but is slow.
code
ruby · 13 linesclass Current < ActiveSupport::CurrentAttributes
attribute :session, :school
delegate :user, to: :session, allow_nil: true
end
# config/application.rb
config.active_record.query_log_tags_enabled = true
config.active_record.query_log_tags = [
:application,
{ school_id: -> { Current.school&.id },
job_id: ->(context) { context[:job]&.job_id } }
]
# Grade Load ... /*action='show',application='GradesPortal',controller='report_cards',school_id='7'*/go deeper
Know that custom tags go in a Hash inside config.active_record.query_log_tags and that their value can be a lambda.
Explain the arity rule, what the context holds (controller, job, connection), and that nil tags are dropped.
Keep tag lambdas cheap and safe, avoid untrusted input, and know that Rails re-adds controller, action and job unless the around options are turned off.
Choose a small, stable tag set, such as tenant and request id, that database and tracing tools across the organisation can rely on.
## Where custom tags go Query log tags (`config.active_record.query_log_tags_enabled = true`) append a comment to every SQL statement. Which pairs appear is decided by `config.active_record.query_log_tags`, an **array** whose elements are either: - a **Symbol**, naming a built-in tag (`:application`, `:pid`, `:socket`, `:db_host`, `:database`, `:source_location`, plus `:controller`, `:action`, `:namespaced_controller` and `:job` from the other frameworks); or - a **Hash**, defining your own tags by name. ```ruby # config/application.rb config.active_record.query_log_tags = [ :application, :namespaced_controller, :action, :job, { request_id: ->(context) { context[:controller]&.request&.request_id }, school_id: -> { Current.school&.id }, portal: "teacher" } ] ``` ## The three kinds of value `ActiveRecord::QueryLogs` turns each entry into a handler when the configuration is applied, choosing by what the value is: | Value | How it is called | Typical use | |---|---|---| | one-argument lambda | `handler.call(context)` | data Rails keeps for the execution: the controller, the job, the connection | | zero-argument lambda | called with no arguments | app state, usually `Current` attributes | | plain value | returned as is | a constant label such as the deployment role | The check is the lambda's **arity**. A lambda declared `->(context)` gets the context; one declared `-> { }` does not and is wrapped so it can be called without it. ## What the context holds The context passed to a one-argument lambda is the current **execution context** plus the connection running the query: 1. `context[:controller]` is the controller instance, set when an action is processed. It gives access to `request`, `params` and anything else on the controller. 2. `context[:job]` is the job instance during `perform`, with `job_id`, `queue_name` and its arguments. 3. `context[:connection]` is the Active Record connection, which is how the built-in `:database` and `:db_host` tags read the configuration. All of them can be absent: a query from a job has no controller, a query from Rack middleware before the action has neither. Use safe navigation (`&.`) and let the lambda return `nil`, because **nil values are omitted** from the comment. ## Rails adds its own tags anyway When tags are enabled, Action Controller adds `:controller` (unless the array already has `:namespaced_controller`) and `:action`, and Active Job adds `:job`, even if your array leaves them out. To stop that, set `config.action_controller.log_query_tags_around_actions = false` or `config.active_job.log_query_tags_around_perform = false`. ## Escaping and safety - Rails sanitises the comment text: it strips a leading `/*` and trailing `*/` and breaks up any `*/` or `/*` inside, so a tag value cannot end the comment and inject SQL after it. - With the SQLCommenter format, values are also URL-encoded. - The API documentation still warns against using untrusted user input. A raw `params[:q]` tag would put user text into every statement and every database log. - Keep values short and low-cardinality enough to be useful: an id is good; a whole serialized object is not. ## Choosing what to tag 1. **Who**: a tenant or school id, so one noisy customer stands out. 2. **Which request**: a request id, so the database statement can be matched to the application log for the same request. 3. **Which job run**: the job id for background work. 4. **Where in the fleet**: `:pid` or `:db_host` when several processes or replicas are involved. Four or five tags are usually enough; every extra tag is more text on every statement. ## Performance - Every lambda runs for **every query**, unless `config.active_record.cache_query_log_tags` is on, which reuses the comment within an execution. Keep lambdas trivial: no queries, no I/O. - `:source_location` walks the call stack per query; the documentation warns it can be slow, so think twice before enabling it in production. With a `school_id` and `request_id` in every comment, a slow statement in the database's own logs names the school, the request and, through the default tags, the controller action that issued it.
- Your query_log_tags array lists only :application and a custom tag, yet comments still include controller and action. Why?Action Controller's railtie adds `:controller` and `:action` to the configured tags whenever query log tags are enabled and `config.action_controller.log_query_tags_around_actions` is true, its default. Active Job does the same with `:job`. Set those options to false to keep them out.
- Why must a tag lambda not run a database query of its own?Tag lambdas run while Active Record is preparing a statement, once per statement unless tag caching is on. A query inside one adds a round trip to every statement in the app and runs back through the same tagging step. Read values that are already in memory, such as `Current` attributes or the controller's request.
- A zero-argument lambda in query_log_tags raises because Rails always passes the context.
- A tag returning nil prints school_id='' in the comment.
- Omitting :controller from query_log_tags always removes it from the comment.
- Tag values are not escaped, so any value can break the SQL comment.
- :source_location is free, so it can be on in production without a thought.