# Rails Structured Event Reporting: Rails.event in Rails 8.1 with JSON Logs

> Rails structured event reporting with Rails.event in Rails 8.1: a JSON subscriber, tags, request context, filtering and tests, with code I ran on 8.1.4.1.

- URL: https://railsdev.io/blog/rails-structured-event-reporting
- Published: 2026-11-08
- Updated: 2026-11-11
- Author: Hendra Nicholas (Rails Full-Stack Developer & AI Engineer)

---

Rails structured event reporting is a feature of Rails 8.1: you call `Rails.event.notify("user.signup", user_id: 123)`, and Rails builds an event with a name, a payload, tags, context, a timestamp and the source location, then hands it to subscribers that you register. Subscribers decide the output, so the same event can become a JSON log line, a message to a log service or an assertion in a test.

This article shows how to set it up in a Rails 8.1 app: a JSON subscriber, tags and request context, the events Rails 8.1 already emits on its own, how sensitive data is filtered, and how to test events. It is written for Rails developers who want searchable logs, and for CTOs and product owners who want to know what an upgrade to 8.1 gives them. If you haven't moved yet, start with the [Rails 8.1 upgrade guide](/blog/rails-8-1-upgrade).

> I ran the examples in this article on a minimal Rails 8.1.4.1 app with Ruby 3.3.6 and SQLite. I used the integration test for the signup example and `rails runner` for the rest. I did not send events to a real log service, so the shipping advice is based on the API, not on a tested setup.

## Why plain Rails logs are hard to use

The default Rails logger writes text for people to read. A line such as `Completed 200 OK in 12ms` is easy to scan in a terminal. It is hard to search, count or alert on, because every question needs a regular expression that breaks when the message changes.

The Rails 8.1 release notes describe the problem in one sentence: the default logger is great for human consumption but less ideal for post-processing. The Event Reporter is the answer from the Rails team. An event is a hash with named fields, so a log tool can filter `status >= 500` without parsing prose.

## How Rails.event works

`Rails.event` is an instance of `ActiveSupport::EventReporter`. It was added in Rails 8.1, which was released on October 22, 2025. Every call to `notify` builds this hash and passes it to each subscriber's `emit` method (field list from the [Rails source](https://github.com/rails/rails/blob/v8.1.4.1/activesupport/lib/active_support/event_reporter.rb)):

| Key | What it holds |
| --- | --- |
| `name` | The event name, as a string |
| `payload` | The hash you passed, or the event object itself |
| `tags` | Tags from the surrounding `tagged` blocks |
| `context` | Metadata for the current request or job |
| `timestamp` | Nanoseconds since the Unix epoch |
| `source_location` | File path, line number and method of the `notify` call |

Three things set it apart from the logger:

- **Nothing is written until you subscribe.** A new Rails 8.1 app has no subscriber for `Rails.event`, so you decide where events go.
- **You own the format.** A subscriber is any object with an `emit(event)` method.
- **Keys are symbols.** String keys in payloads, tags and context are converted to symbols.

## Step 1: Write a JSON subscriber

This subscriber writes one JSON object per line. That format (JSON Lines) is what most log tools can ingest. It also handles event objects, which are passed through to subscribers as they are:

```ruby
# app/subscribers/json_event_subscriber.rb
class JsonEventSubscriber
  def initialize(io)
    @io = io
  end

  def emit(event)
    payload = event[:payload]
    payload = payload.serialize if payload.respond_to?(:serialize)

    @io.puts JSON.generate(event.merge(payload: payload))
  end
end
```

Register it in an initializer. I used `after_initialize` so the class is autoloaded and `Rails.root` is ready:

```ruby
# config/initializers/event_subscribers.rb
Rails.application.config.after_initialize do
  log = Rails.root.join("log/events.jsonl").open("a")
  log.sync = true

  Rails.event.subscribe(JsonEventSubscriber.new(log))
end
```

I wrote to a file so I could read the result. In a container you would usually write to `$stdout` instead and let the platform collect it, for example on a server you deploy with [Kamal](/blog/kamal-rails). I did not test that setup.

## Step 2: Report your own events

Call `notify` with a name and keyword arguments (or a hash). `tagged` adds tags to every event inside the block:

```ruby
# app/controllers/signups_controller.rb
class SignupsController < ApplicationController
  def create
    Rails.event.tagged("signup") do
      Rails.event.notify(
        "user.signup",
        email: params[:email], password: params[:password], plan: "free"
      )
    end
    head :created
  end
end
```

Posting to this action produced this line in `log/events.jsonl` (I added the line breaks):

```json
{"name":"user.signup",
 "payload":{"email":"[FILTERED]","password":"[FILTERED]","plan":"free"},
 "tags":{"signup":true},
 "context":{"request_id":"bc102705-10b1-408a-b5a1-d1105eb0be8e"},
 "timestamp":1794131582955905373,
 "source_location":{"filepath":"/tmp/er/app1/app/controllers/signups_controller.rb",
  "lineno":4,"label":"block in create"}}
```

Note that `email` and `password` are already `[FILTERED]`, and I did nothing to make that happen. More on this below.

A naming convention helps later. I use `noun.past_tense_verb` (`user.signup`, `invoice.paid`) so a subscriber can match a whole family with `start_with?("invoice.")`.

## Step 3: Add request context

Tags describe a block of code. **Context** describes the current request or job and is added to every event. Set it with `set_context`:

```ruby
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_event_context

  private

  def set_event_context
    Rails.event.set_context(request_id: request.request_id)
  end
end
```

The `context` field in the JSON above shows the result. Per the Rails source, context is cleared before and after each request and job, so values don't leak between them. You can replace the store with `config.active_support.event_reporter_context_store` if you need something custom.

One pitfall I hit: Rails also emits `action_controller.request_started`, and in my run its `context` was empty. A `before_action` runs after that event, so the request ID reached `request_completed` and my own events, but not the first one. If you need the ID on every event, set it earlier than a controller callback. I did not test where, so check the result in your app.

## Events Rails 8.1 already emits

You get data before you write any `notify` call. In my test app the framework reported these events:

| Event name | When | Payload fields I saw |
| --- | --- | --- |
| `action_controller.request_started` | A request reaches an action | controller, action, format, params |
| `action_controller.request_completed` | The action finishes | status, duration_ms, db_runtime, queries_count |
| `active_job.started`, `active_job.completed` | A job runs | job_class, job_id, queue, arguments |
| `active_record.sql` | A query runs (development only in my run) | sql, name, duration_ms |
| `action_view.render_*` | A template or partial renders (development only in my run) | identifier, duration_ms |

The `source_location` of these events points to `structured_event_subscriber.rb` files inside Action Pack, Active Record, Active Job and Action View. That list comes from one small app, so don't treat it as complete. Print `event[:name]` in a throwaway subscriber to see what your own app produces.

Because every subscriber receives all of these events, **filter early**. A subscriber can take a block, and it only receives events for which the block is truthy:

```ruby
Rails.event.subscribe(JsonEventSubscriber.new(log)) do |event|
  event[:name].start_with?("user.", "invoice.", "action_controller.")
end
```

## Debug events and the development-only noise

`Rails.event.debug` reports an event only when the reporter is in debug mode. Rails turns debug mode on in development and leaves it off elsewhere. This is how `active_record.sql` and `action_view.render_*` stayed out of my production-mode run, and it is a good place for your own chatty events:

```ruby
Rails.event.debug("search.query", sql: relation.to_sql)

Rails.event.with_debug do
  Rails.event.debug("search.query", sql: relation.to_sql) # reported
end
```

In my run, `Rails.event.debug_mode?` returned `true` in development and nothing truthy in production. The `with_debug` block reported the event in both. That block is a handy way to turn on detail for one slow code path while you investigate it.

## Sensitive data: what is filtered and what is not

Hash payloads are filtered with your app's `filter_parameters`. The generated `config/initializers/filter_parameter_logging.rb` includes `:passw`, `:email` and `:secret`, which is why my signup event shows `[FILTERED]` for both fields. If you want the email in your analytics events, remove `:email` from that list, and think about who can read the logs first.

One more catch from my run: the `active_job.started` event carried `"arguments":["a@example.com"]` unfiltered. The filter works on hash keys, and job arguments are a plain array, so an email passed to a job showed up in clear text. Pass IDs to jobs, not personal data, or drop that event from your subscriber's filter.

Event objects are different. If you pass an object instead of a hash, it reaches subscribers as it is, and the Rails docs say the subscriber must filter it. This is the safest approach:

- Prefer hash payloads for anything with user data.
- If you use event objects, build the filtered hash in `serialize` or run `ActiveSupport::ParameterFilter` in the subscriber.
- Never put tokens, full request bodies or card data in a payload, filtered or not.

I would also keep `[FILTERED]` as a safety net, not as the plan. The plan is to not report the data at all.

## Testing events

Rails 8.1 ships test helpers for the reporter. This test passed on my app:

```ruby
# test/integration/signup_test.rb
require "test_helper"

class SignupTest < ActionDispatch::IntegrationTest
  test "signup reports an event" do
    assert_event_reported("user.signup",
      payload: { plan: "free" }, tags: { signup: true }) do
      post "/signups", params: { email: "a@example.com", password: "secret" }
    end
    assert_response :created
  end

  test "debug events are skipped by default" do
    assert_no_event_reported("sql.debug") do
      Rails.event.debug("sql.debug", sql: "SELECT 1")
    end
  end
end
```

The expected payload is a subset: I listed only `plan`, and the test passed although the event has other keys. The Rails changelog also lists `assert_events_reported` for several events in one block and `with_debug_event_reporting` for testing debug events. I read those in the source but did not run them.

This is where events beat log lines. Asserting that "a signup was reported with the free plan" is stable, while asserting on a log message breaks when someone rewords it.

## Rails.event vs the alternatives

| Option | Best for | Limit |
| --- | --- | --- |
| `Rails.logger` | Human-readable messages and debugging | Free text, hard to query |
| `ActiveSupport::Notifications` | In-process instrumentation: timing a block, reacting to framework hooks | Not a logging format; you build the output |
| `Rails.event` | Structured business and framework events for logs, analytics and tests | New in 8.1, and you write the subscriber |
| JSON log formatters (for example [lograge](https://github.com/roidrage/lograge)) | One JSON line per request with minimal setup | Request-focused, not an API for your own events |

They aren't exclusive. Your app keeps writing its normal text logs when you add a subscriber, and I saw both in my production-mode run. I would add `Rails.event` for business events (signups, payments, plan changes) and keep `Rails.logger` for debugging output.

## Limits and production checklist

- [ ] **Rails 8.1 or newer.** `Rails.event` doesn't exist before 8.1. Rails 8.0 stops receiving security fixes on November 7, 2026, so an upgrade is due anyway.
- [ ] **A subscriber that never raises.** If a subscriber raises, Rails reports the error through `Rails.error` and carries on. In development it raises instead, because `raise_on_error` follows `consider_all_requests_local` (per `railties` source).
- [ ] **Filtered subscriptions.** Send only the event names a destination needs, so logs and costs stay predictable.
- [ ] **No secrets in payloads or job arguments.** Filtering is a net, not a plan, and it did not cover job arguments in my run.
- [ ] **Event names are an API.** Dashboards and alerts depend on them, so don't rename them casually.
- [ ] **Background jobs covered.** Context is cleared per job, so set it again inside jobs that need a request or tenant ID. Pair this with [resumable jobs](/blog/rails-active-job-continuations) or [Solid Queue](/blog/solid-queue-rails) so long jobs report progress.
- [ ] **A load check.** I did not measure the overhead of many events per request. Measure it before you subscribe to `active_record.sql` on a busy endpoint. My [guide to scaling a Rails app](/blog/scaling-ruby-on-rails) covers measuring first.

If your logs are a pile of text today and you want searchable events, alerts and a safe path to Rails 8.1, my [Ruby on Rails consulting](/services/ruby-on-rails-consulting) work includes this kind of review.

For caching, see [Solid Cache in Rails 8](/blog/solid-cache-rails).

## Conclusion

Rails structured event reporting turns logging into data: named events with tags, context and filtered payloads, delivered to subscribers you control, and testable with `assert_event_reported`. A JSON subscriber with a name filter is about twenty lines and gives you queryable logs without a new gem. Start with a few business events, keep sensitive values out of payloads, and set request context as early as you can.

I help teams adopt Rails 8.1 features like this one safely: upgrades, logging and observability, and performance reviews of production apps. If you want an experienced Rails developer to set this up or to review your upgrade plan, [send me a short brief and book a discovery call](/#contact).

## Frequently asked questions

### What is Rails.event?

It is the structured event reporter added in Rails 8.1, an instance of `ActiveSupport::EventReporter`. You report events with `Rails.event.notify`, and subscribers you register receive them as hashes. It reports nothing anywhere until you add a subscriber.

### Which Rails version has structured event reporting?

Rails 8.1 and newer. It is listed in the Rails 8.1 release notes. Rails 8.0 and older don't have `Rails.event`.

### Does Rails.event replace Rails.logger?

No. In my test the normal text logs kept working next to the events. `Rails.logger` suits human-readable messages, and `Rails.event` suits data you want to query, count or test.

### How is Rails.event different from ActiveSupport::Notifications?

`ActiveSupport::Notifications` is an in-process instrumentation system, good for timing a block or reacting to a hook. `Rails.event` produces structured records with tags, context and filtering for outside consumers. The Rails 8.1 framework events I inspected come from `structured_event_subscriber.rb` files, so the two work side by side.

### How do I send Rails events as JSON?

Write a subscriber with an `emit(event)` method that calls `JSON.generate(event)`, and register it with `Rails.event.subscribe`. The example in Step 1 does this and also handles event objects through `serialize`.

### Are sensitive values filtered in events?

Hash payloads are filtered with your `filter_parameters`. Event objects are not, so the subscriber has to filter them. Keep secrets and personal data out of payloads regardless.

### Can I test that an event was reported?

Yes. Use `assert_event_reported(name, payload:, tags:)` and `assert_no_event_reported`. I ran both on Rails 8.1.4.1. The payload you pass is matched as a subset.

## References

- [Ruby on Rails 8.1 release notes: Structured Event Reporting](https://guides.rubyonrails.org/8_1_release_notes.html)
- [Rails 8.1 release announcement, October 22, 2025](https://rubyonrails.org/2025/10/22/rails-8-1)
- [`ActiveSupport::EventReporter` source, v8.1.4.1](https://github.com/rails/rails/blob/v8.1.4.1/activesupport/lib/active_support/event_reporter.rb)
- [`ActiveSupport::EventReporter` API documentation](https://api.rubyonrails.org/classes/ActiveSupport/EventReporter.html)
- [Active Support changelog, v8.1.4.1](https://github.com/rails/rails/blob/v8.1.4.1/activesupport/CHANGELOG.md)
- [Rails maintenance policy](https://rubyonrails.org/maintenance)
