skip to content

Logs, Errors & Debuggers

Finding out what a Rails app is doing: the tagged logger and parameter filtering, the debug gem and web console, the Rails.error reporter and SQL query tags. Interviewers ask how you chase a bug.

part ofRuby on Railsread it →
on this pageshow

explore

questions

21

In a Rails 8.1 app, how do you pause a request inside a controller action or model method, and what does the generated Gemfile contribute?

level: juniorimportance: must knowfreq 60%

answer

  1. one method call on the line
  2. development and test group
  3. require: "debug/prelude"
  4. prompt in the bin/rails server terminal
  5. the browser waits meanwhile

basics

~20 s

Put debugger, or binding.break, on the line you want to inspect. The generated Gemfile loads the debug gem in development and test with require: "debug/prelude", so the call opens an rdbg prompt in the terminal running the server while the request waits.

solid answer

~40 s

A new Rails 8.1 app has `gem "debug", platforms: %i[ mri windows ], require: "debug/prelude"` in the `:development, :test` group. The prelude only defines `Kernel#debugger` and the `binding.break` and `binding.b` aliases. The debugger itself loads on the first call, so boot does not pay for it. Drop `debugger` into `CartsController#show` or a model method such as `Cart#discount_total`, reload the page, and the terminal running `bin/rails server` shows the source around that line and an `(rdbg)` prompt. The browser's request hangs until you continue. You can read `@cart`, `params` or locals, then continue. Because only development and test require the gem, a `debugger` left in committed code raises `NameError` in production, and the omakase RuboCop config does not flag it.

go deeper

for a junior

Recall that debugger or binding.break pauses the request and that the prompt appears in the terminal running the server, not in the browser.

for a middle

Explain the Gemfile line: the development and test group, the platforms option, and why debug/prelude loads the debugger lazily.

for a senior

Show how you keep breakpoints out of production, knowing the gem is not loaded there and the omakase RuboCop config will not flag them.

for a principal

Decide how the team debugs locally versus in shared environments, and what guardrails keep interactive breakpoints out of deployed code.

## What the generated app sets up `rails new` writes this into the `Gemfile`: ```ruby group :development, :test do # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" end ``` Three details matter: - **The group.** Bundler requires the `:development` and `:test` groups only in those environments (`Bundler.require(*Rails.groups)` in `config/application.rb`). Production never loads the gem. - **`platforms: %i[ mri windows ]`.** The debug gem is built for CRuby, so other Ruby implementations skip it. - **`require: "debug/prelude"`.** Requiring `"debug"` itself would load the debugger and start a session while the app boots. The **prelude** is tiny: it defines `Kernel#debugger` and aliases `Binding#break` and `Binding#b` to it. The real debugger is loaded on the **first call**, so a normal boot pays nothing. ## Setting a breakpoint Say a toy store's cart page shows the wrong discount. You suspect the model, so you stop there: ```ruby class Cart < ApplicationRecord has_many :line_items def discount_total debugger line_items.sum { |item| item.price * item.discount_rate } end end ``` Reload the cart page. Here is what happens: 1. The request runs through the router, the controller and into `Cart#discount_total` on a Puma thread. 2. `debugger` loads the debug gem, opens a session and suspends at that line. 3. The terminal running `bin/rails server` prints the surrounding source, the current frame and an `(rdbg)` prompt. 4. The browser shows its loading indicator, because the response has not been written yet. While the session is suspended, the debug gem also pauses the process's other threads, so other pages wait too. 5. You evaluate Ruby at the prompt, for example `line_items.map(&:discount_rate)` or `self`. When you tell the debugger to continue, the request finishes and the page renders. `binding.break` and `binding.b` do the same thing. The guide uses `debugger` because it reads well in a controller. ## Where the prompt appears | Code path | Where the prompt shows | |---|---| | Controller action or model method during a page load | The terminal running `bin/rails server` | | The same method called from a test | The terminal running `bin/rails test` | | A job run by the default `:async` adapter in development | The server terminal, since jobs run on the server's threads | | The method called from `bin/rails console` | The console session itself | When nobody is watching the terminal, the request simply waits. That is the most common "my page hangs" report from a teammate who left a breakpoint in. ## Choosing where to stop Rails developers usually have three ways to look inside a running request, and each fits a different moment: - **`debugger`** stops *before* something goes wrong, in a terminal, and lets you step forward line by line. It is the tool when you know roughly where the bad value appears. - **`console` from web-console**, called in an action or view, gives you a Ruby console in the browser for the page you are looking at, with no terminal involved. - **The exception page's console** appears *after* something raised, bound to the frame that raised. It is ideal when the code already fails loudly. A wrong discount that raises nothing calls for `debugger` or `console`. A `NoMethodError` on `nil` is usually solved on the exception page. ## Leaving breakpoints behind - **Production.** The gem is not required there, so a `debugger` line raises **`NameError`** (undefined local variable or method `debugger`) when that code runs. One forgotten line turns a working checkout into a 500. - **Linting.** The generated `.rubocop.yml` inherits `rubocop-rails-omakase`, which disables the whole `Lint` department. Nothing flags a stray `debugger` unless you enable a cop for it yourself. - **Habit.** Search the diff for `debugger` and `binding.b` before committing, or add a check to your CI. ## Why not `puts` or the logger? A log line tells you what you thought to print in advance. A breakpoint lets you ask questions you only think of once you see the state: an association that is unexpectedly loaded, a `params` key spelled differently, a discount rate stored as an integer. Logs are better for timing and for production. Breakpoints are better when you can reproduce the bug locally. ## Takeaway The Gemfile line makes `debugger` available in development and test at no boot cost. You put the call on a line, trigger the code path, and use the prompt in whichever terminal runs that code. Delete the line before it ships, because production does not have the method.

  • Why does the generated Gemfile say require: "debug/prelude" instead of letting Bundler require "debug"?
    Requiring `"debug"` loads `debug/session` and starts a debugger session while the app boots, unless `RUBY_DEBUG_LAZY` is set. `debug/prelude` only defines `Kernel#debugger` and the `binding.break` and `binding.b` aliases, which load the real debugger on first use. Boot stays fast and no session exists until you actually stop somewhere.
  • A colleague's `debugger` line reached production. What happens when a customer hits that code?
    Production does not require the `:development, :test` group, so `debugger` is undefined there. Ruby raises `NameError` at that line and the request fails with a 500, or the job fails. Nothing caught it earlier because the omakase RuboCop config disables the `Lint` department. A search for `debugger` in the diff, or a CI check, is the safeguard.

  • You must add require "debug" at the top of the controller before calling debugger.
  • The debugger prompt opens in the browser tab that made the request.
  • require: "debug/prelude" starts a debugger session every time the app boots.
  • A leftover debugger call is a no-op in production, so it is harmless.
  • The generated RuboCop config fails the build on a stray debugger call.
  • debugger only works in controllers, not in models or jobs.
open as a page

In a Rails app, what does Rails.error.report do with an exception you rescued, and what do its handled: and severity: options default to?

level: juniorimportance: must knowfreq 40%

basics

~10 s

Rails.error.report(error) hands an exception you already rescued to every registered error subscriber, then returns nil without re-raising it. handled: defaults to true, and severity: defaults to :warning when handled, :error when handled: false.

open as a page

In a Rails 8.1 app, which log level does each environment run at, and how do you change production's without a code change?

level: juniorimportance: must knowfreq 58%

basics

~10 s

Development and test log at debug, Rails' own default. The generated production.rb sets config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info"), so production runs at info until you set RAILS_LOG_LEVEL and restart.

open as a page

In a Rails 8.1 development log, what do verbose_query_logs and verbose_redirect_logs add, and why are they left off in production?

level: juniorimportance: must knowfreq 35%

basics

~20 s

Both add a ↳ line naming the line of your own code behind the entry: verbose_query_logs under each SQL statement, verbose_redirect_logs (new in 8.1) under each redirect. Each walks the call stack, so only development enables them.

open as a page

In Rails, how do Rails.error.handle and Rails.error.record differ in what they report, return and re-raise when the block fails?

level: middleimportance: must knowfreq 45%

basics

~20 s

Rails.error.handle reports a failure as handled with severity :warning, swallows it and returns nil or fallback.call. Rails.error.record reports it as unhandled with severity :error and re-raises it. Both return the block's value when nothing fails.

open as a page

In Rails 8.1, how do config.filter_parameters and filter_attributes keep a card number out of the logs, and what still leaks?

level: middleimportance: must knowfreq 55%

basics

~20 s

Add the key to config.filter_parameters, for example :card_number, which the default list does not cover. Rails then logs [FILTERED] in the Parameters line, the query string, record inspect output and SQL binds. Values you interpolate into your own log lines still leak.

open as a page

In Rails 8.1 development, what does the exception page show when an action raises, and how do you use it to find the bug?

level: juniorimportance: should knowfreq 48%

basics

~20 s

ActionDispatch::DebugExceptions renders the exception class, controller and action, message, source around the failing line, the application trace and the request's parameters and headers. web-console adds a live console in the failing frame. Rails 8.1 adds a Copy as text button.

open as a page

In a Rails request log, what do the Started, Processing by, Parameters and Completed lines each tell you about one request?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Started gives the verb, path, client IP and time. Processing by names the controller, action and format, and Parameters shows the filtered params. Completed gives the status and total milliseconds, split into Views, ActiveRecord with query counts, and GC.

open as a page

When bin/dev runs a Rails app through foreman, why is a debugger prompt unusable, and how do you attach to the stopped request?

level: middleimportance: should knowfreq 30%

basics

~20 s

Foreman pipes each process's output through itself and prints it line by line, so the web process's interactive prompt does not work reliably. Start the server with RUBY_DEBUG_OPEN=true, so the debugger opens a socket, and attach from another terminal with rdbg --attach.

open as a page

With Rails' web-console gem, how do you open a console in a view or controller, and what does config.web_console.permissions control?

level: middleimportance: should knowfreq 30%

basics

~20 s

Call console in a view or controller action and web-console appends a Ruby console, bound to that context, to the HTML page. config.web_console.permissions lists the extra IP addresses or networks allowed to see it; localhost is always allowed.

open as a page

In a Rails controller, how do Rails.error.set_context and the context: option attach details such as the current user to error reports?

level: middleimportance: should knowfreq 25%

basics

~20 s

Rails.error.set_context stores key-value pairs for the current request or job; every later report merges them with its own context: hash, the call's keys winning, and passes the result to subscribers. Rails clears the store when the execution ends.

open as a page

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%

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.

open as a page

In a Rails development log, what do Grade Load (12.4ms), CACHE Grade Load (0.0ms) and ActiveRecord: 350.1ms (48 queries, 6 cached) each measure?

level: middleimportance: should knowfreq 35%

basics

~20 s

Grade Load (12.4ms) is the time one SELECT took inside the database adapter, as measured from Ruby. CACHE means Active Record's query cache answered it without the database. ActiveRecord: 350.1ms (48 queries, 6 cached) totals every statement in the action.

open as a page

In Rails 8.1, what does config.active_record.query_log_tags_enabled add to each SQL statement, and how do the SQLCommenter and legacy formats differ?

level: middleimportance: should knowfreq 25%

basics

~20 s

It makes Active Record append a SQL comment naming the application and the controller and action, or the job, to every statement it sends. SQLCommenter, the default since load_defaults 7.1, writes key='url-encoded value' pairs; the legacy format writes key:value.

open as a page

A Rails toy store applies the wrong discount only to some carts; how do you reproduce it and break only on the failing case?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Capture a failing cart in a test, then guard the breakpoint with a Ruby condition, such as debugger if line_items.any? { _1.discount_rate.nil? }, in the method that computes the discount. Run that single test so only the bad case stops.

open as a page

In a Rails 8.1 app, how do you write and register an error subscriber that forwards Rails.error reports to an error tracker?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Write an object whose report(error, handled:, severity:, context:, source:) method calls the tracker's client, and register it with Rails.error.subscribe in an initializer. Every report, manual or from Rails' request and job wrappers, then reaches the tracker.

open as a page

In a Rails 8.1 app with no rescue code of your own, how does an exception raised in a controller action or an Active Job reach Rails.error subscribers?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rails runs every request and job inside its executor. ActionDispatch::Executor reports an escaping request error with handled: false, and the executor around each job reports whatever perform lets escape. rescue_responses classes, such as 404s, are skipped.

open as a page

Since Rails 7.1, Rails.logger is an ActiveSupport::BroadcastLogger; how do you add a second log sink in production, and what traps come with it?

level: seniorimportance: should knowfreq 24%

basics

~20 s

Call Rails.logger.broadcast_to(sink) in an initializer and every line also goes to that sink. Give the sink the app's formatter so request-id tags appear, set its level, and remember that Rails.logger.level reports the lowest level of any sink.

open as a page

A slow statement shows up in the production database's logs of a Rails 8.1 grades portal; how do you trace it to the controller action or job, and what does that cost?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Enable query log tags in production so every statement carries a comment naming the controller and action, or the job; the slow statement in the database's logs then names its origin. The cost is prepared statements and some work per query.

open as a page

In Rails, what does Rails.error.unexpected do, and why does the same call raise in development but only report in production?

level: middleimportance: nice to knowfreq 15%

basics

~10 s

Rails.error.unexpected flags a broken assumption. With debug_mode on (consider_all_requests_local, so development and test) it raises ActiveSupport::ErrorReporter::UnexpectedError; otherwise it reports the error as handled with severity :warning and returns nil.

open as a page

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?

level: middleimportance: nice to knowfreq 12%

basics

~20 s

Add 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.

open as a page