0.0
The project is in a healthy, maintained state
Captures HTTP requests, background jobs, and database changes from Rails applications. Events are automatically correlated and sent to EzLogs Server, where they are transformed into human-readable activity stories.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Development

~> 2.2
>= 7.0
~> 3.12
~> 7.0
~> 2.9
~> 3.18
>= 0.109

Runtime

 Project Readme

EZLogs for Rails

Website · Documentation · Next.js agent · Supabase

Know what your app and its AI agents did, in plain English.

This gem records what happens in your Rails app (requests, background jobs, database changes, calls to outside services) and sends it to EZLogs. There, each thing someone did becomes one card anyone in your company can read, support and founders included:

00:28  Marked booking 'BRK-FQYA' as rebooked
       Changed the status from disrupted to rebooked and changed the sailing
       Agent · Rebooking assistant · 1 entity

00:27  Refund 'RF-3JRW' failed
       Changed the status from pending to failed (card expired, 32.10 EUR)
       Reason: Card expired (card ending 0069)
       Agent · Rebooking assistant · 2 entities

00:26  Marked sailing 'Wed 07:10 Brackwater → Holm' as cancelled
       Changed the status from scheduled to cancelled, marked 30 bookings as disrupted
       Tomás Rivera · 31 entities

The request, the jobs it queued and every row they changed land in one card, with who did it: a person, an AI agent or the system. On top of that you get:

  • Pulse: where every person and every record stands right now.
  • Alerts: pin a question ("tell me when a refund fails"), get an email or a Slack message.
  • MCP: your own AI (Claude, ChatGPT, Cursor) can read what happened and answer from it.
  • Shares: signed links, embeds and signed audit exports.

The agent only reads. It never changes anything in your app, never blocks a request, and drops passwords, tokens and other secrets before anything leaves your app. From 0.2.24 it also masks phone numbers, addresses, birth dates, IP addresses and identity-document numbers: EZLogs records that one changed, never its value. Same wire format as the Next.js agent, so a Rails back end and a Next.js front end show up in one timeline.

Fastest install: paste this into Cursor, Claude Code or any coding AI:

Install EZLogs in this app by following https://app.ezlogs.io/install/rails.md

Or follow the steps below. Free while in beta: sign up.

EZLogs is not a monitoring or metrics tool and does not replace Sentry or your APM. It tells people what happened, in words.


Installation

Step 1: Add the Gem

Add to your Gemfile:

gem 'ez_logs_agent'

Then install:

bundle install

Step 2: Run the Generator

rails generate ez_logs_agent:install

This creates config/initializers/ez_logs_agent.rb with all available configuration options and helpful comments.

Requirements

  • Ruby >= 3.1.0
  • Rails 7.0+. On Rails 7.2 and later a write inside a transaction that rolls back is not sent (past 10,000 changes in one transaction, the rest are sent at once). Rails 7.0 and 7.1 have no public hook for that, so there a rolled-back write is still sent and shows as done; both versions are past their security support, and upgrading to 7.2 fixes it.
  • Sidekiq (optional, auto-detected if present)
  • ActiveRecord (optional, auto-detected if present)

Quick Start

1. Get Your API Key

Sign up for EZLogs at app.ezlogs.io and create an API key from your dashboard settings.

2. Configure the Agent

Edit config/initializers/ez_logs_agent.rb:

EzLogsAgent.configure do |config|
  # Required: Your API key from the EZLogs dashboard
  config.project_token = "ezl_your_api_key_here"
end

server_url defaults to ENV["EZLOGS_SERVER_URL"] if set, otherwise https://app.ezlogs.io. Set it only if you self-host.

That's it. The agent handles everything else automatically:

  • No middleware registration needed
  • No Sidekiq configuration required
  • No ActiveRecord setup necessary

The agent orchestrates itself via a Rails Railtie. When your app boots, event capture begins automatically.

3. Verify It's Working

Test your configuration:

rails ez_logs_agent:test_connection

Successful output (excerpt):

✅ Configuration is valid
✅ Connection successful (HTTP 200)
   Test event accepted by server

✅ All checks passed! EzLogs Agent is configured correctly.

If the test fails, you'll see exactly what's wrong and how to fix it.

4. Restart Your Application

# Development
rails server

# Production
# Restart your application using your deployment process

Check your Rails logs for the startup line. It is printed once per process (web, Sidekiq, rake), whatever the agent's log_level, and is visible unless Rails' own log level is above info. In development it lands in log/development.log (rails s copies the log to the terminal only after boot). Silent in the test env.

[EzLogsAgent] capturing → app.ezlogs.io (key ezl_a1b2c3d4…)

The key is shown the way Install & keys shows it (ezl_ + first 8 characters), so you can tell which key the app uses. If something is missing, the line says what:

[EzLogsAgent] not capturing: project_token missing

Set project_token in config/initializers/ez_logs_agent.rb. The agent checks it once at boot, so a token set later (in after_initialize or to_prepare) is not seen.

5. See Your Activity

Visit your EZLogs dashboard and interact with your application. Within seconds, you'll see activity appearing in real-time.


What Gets Captured

EZLogs Agent captures three primary event sources. These are the building blocks that EZLogs Server uses to construct complete activity stories.

1. HTTP Requests

Every incoming HTTP request, with intelligent noise filtering:

What's captured:

  • HTTP method, path, status code, duration
  • Controller and action name (for Rails apps)
  • GraphQL operation name and type (queries, mutations, subscriptions)
  • Request parameters (sanitized automatically)
  • Correlation ID (generated automatically)

Automatic exclusions (no configuration needed):

  • /rails/active_storage* — File uploads/downloads
  • /assets*, /packs*, /vite* — Static assets (JavaScript, CSS, images)
  • /health*, /up, /alive, /ready, /metrics — Health checks + ops endpoints
  • /favicon.ico, /.well-known*, /robots.txt, /sitemap.xml — Crawler / browser plumbing
  • /cable* — ActionCable WebSocket connections
  • /sidekiq, /sidekiq/* — Sidekiq Web UI (auto-polls every few seconds)
  • /hotwire-livereload, /rails/info, /rails/mailers, /__better_errors/* (and their sub-paths) — development-only reload channel and pages
  • Loading (GET, HEAD) */sign_in*, */login*, /users/password*, /session* — Auth pages (Devise + common patterns). Signing in, signing out (any method, a GET /logout link included) and resetting a password are recorded.

Secrets inside values: every string and key the agent sends (params, job arguments, row values, display names, error messages) is checked by its shape, whatever its key:

  • URLs: a URL (scheme://…, alone or inside a text, also URL-encoded as https%3A%2F%2F…) keeps its scheme, host and path; its user:pass@ and everything from ? or # (or %3F, %23) are removed. A value that is a path on its own (/first_password/edit?reset_password_token=…, //cdn/x.png?sig=…) loses its query and fragment too. Inside such a URL or path, a segment that looks generated (16+ characters with a lowercase letter, an uppercase letter and a digit, never a file name with a .: Slack and Discord webhook tokens, /reset/<token>) and a Telegram bot<digits>:<token> segment become [FILTERED]. The event's own request or outbound path keeps its segments (its query and card numbers still go): titles read the ids there.
  • Known shapes: JWTs, private keys, Stripe / Stripe webhook / OpenAI-style (sk- with a digit) / GitHub / Slack / AWS keys, and any 15-16 digit number that passes the Luhn check (card numbers, wherever they sit) become [FILTERED].
  • Bearer / Basic: the word after Bearer is masked when it has a digit or symbol, a lowercase-then-uppercase pair (base64) or 16+ characters; after Basic, the same with 8+ characters.
  • Mailer jobs: in an ActionMailer job (mailer class, method, then deliver_now / deliver_later) whose method has a secret word (reset_password_instructions, confirmation_instructions, unlock_instructions, invitation_instructions, …), every positional string is masked except method names, GlobalIDs, numbers and UUIDs, so the token Devise passes is never sent. Any other job's arguments are left to the rules above (["card_declined", "Order 42 for Alice"] stays).
  • Keys are checked the same way (two keys masked alike both stay: [FILTERED], [FILTERED] 2), and anything nested deeper than 8 levels is sent as [Object]. Error messages are cut to 4 KB like every other string. What this costs, on purpose: a URL's query and fragment are dropped even when they are ordinary data (youtube.com/watch?v=… reads as youtube.com/watch); any 15-16 digit number that passes Luhn is masked, so are some order ids and IMEIs; a slug, username or random id of 16+ characters with mixed case and digits inside a link in a value (a nanoid, github.com/JohnDoe2024Developer) is masked; file names are not. Not masked: a token in the request's own route path (GET /reset/<token>), a known limit until the agents send the route pattern; a link without scheme:// inside a sentence (see /reset?token=…), a text that is not a URL (reset_password_token=abc; its key is still filtered by name), and a short lowercase or letters-only word after Bearer / Basic (Bearer of bad news, Basic Monthly, Basic 2; this also lets through a real but unusual credential such as Bearer abcdef).

Personal values (0.2.24): phone numbers, postal addresses (street, address lines, house number, postcode or zip), precise locations (latitude, longitude), birth dates, IP addresses and identity-document numbers (passport, national, tax or VAT id, ID card, driver's licence) are sent as [FILTERED]. A change to one is still sent, without its values, so EZLogs reads "changed the phone", "set the address", "removed the phone", never the number.

  • By name: the same rule as the Next.js agent, the Supabase install and the EZLogs server (EzLogsAgent::PersonalFields). It applies to row changes and new rows, update_all SET values and WHERE binds, request params and GraphQL variables at any depth, and job arguments by key. A phone written with its country code (+40 721 000 333) or an IP address passed to a job by position is masked too.
  • Not masked: a key ending in id, ids, uuid, type, kind, count, at, status, state, verified or confirmed (address_id, phone_confirmed_at, phone_status), an email (email, email_address: it names who did what), and nil, blank and true/false values (phone_verified: true).
  • By model: a model or table that is itself a list of phones, addresses or IPs (PhoneNumber, user_addresses) has its value columns treated as personal, and its records are never named by their values.
  • The EZLogs server applies the same rule on arrival, so with an older agent version these values are still never stored.
  • The IP address of each request is still sent with it (remote_ip): the EZLogs server drops it on arrival and never stores it. What this costs, on purpose: the rule reads names, not intent, so a business's own address or phone is hidden too; searching EZLogs for a phone number finds nothing; there is no switch to send these values. Health or other special-category data can't be recognised by a column name: leave it out with excluded_tables or excluded_graphql_variable_keys (any key name, everywhere).

Note on GraphQL: All GraphQL operations (queries, mutations, subscriptions) are captured. The server classifies queries as "background" significance, allowing users to toggle their visibility in the UI since they're typically read-only operations.

2. Background Jobs

Sidekiq and ActiveJob executions:

What's captured:

  • Job class name, queue name, duration
  • Success or failure status with error message (if failed)
  • Correlation ID (automatically inherited from the request that enqueued the job)
  • Job arguments (sanitized automatically)

Automatic exclusions (no configuration needed):

  • SidekiqAlive::Worker — Sidekiq liveness probe
  • SolidQueue::CleanupJob — SolidQueue maintenance job
  • SolidQueue::RecurringJob — SolidQueue scheduler internals

Supported job systems:

  • Sidekiq (fully supported)
  • ActiveJob with any backend (fully supported)

3. Database Changes

ActiveRecord create, update, and destroy operations:

What's captured (per-row, via after_create / after_update / after_destroy):

  • Model class name, record ID, operation type (create/update/destroy)
  • For creates: initial attribute values
  • For updates: one meaningful attribute change (e.g., status: pending → shipped)
  • For destroys: final attribute values before deletion
  • Correlation ID (automatically inherited from the current request or job)

What's captured (bulk, via ActiveSupport::Notifications on sql.active_record):

  • The four ActiveRecord operations that bypass per-row callbacks: delete_all, update_all, insert_all, upsert_all.
  • For each: model class, row count, the filter rule (WHERE columns + sanitized bind values), and operation-specific detail (SET hash for update_all, column names for insert_all / upsert_all — values are NOT shipped for bulk inserts).
  • dependent: :delete_all cascades during a parent destroy.

What's NOT captured:

  • SELECT queries (read operations don't change data)
  • Schema migrations (Rails internal operations)
  • Raw connection.execute(sql) calls (no recognizable model class)
  • Individual row IDs affected by bulk operations (only the filter rule and row count — pulling the IDs would require modifying the customer's SQL, which violates the read-only principle).

Automatic exclusions (no configuration needed):

  • sessions — Session store updates
  • schema_migrations, ar_internal_metadata — Rails schema management
  • active_storage_* — ActiveStorage internal tables
  • solid_queue_*, solid_cache_*, solid_cable_* — Solid* gem internals

4. Changes made by hand or on a schedule

A change made outside any request or job reads as an action too, named after what ran it:

Where One action per Shown as
rails console (IRB or Pry) line that changes data "Rails console (deploy)", from the OS account (USER) that opened it
rake / bin/rails some:task task (a task invoked from its body joins it; each prerequisite is its own) "rake orders:backfill"
rails runner (cron's usual entry point) script "rails runner"

Only database changes are grouped there; a line that only reads makes no action. A run longer than 10 minutes continues as a new action with the same name every 10 minutes. A job enqueued there joins that action, as a job enqueued in a request does (an after_commit callback of a record the line updated, for instance), up to 100 jobs per action: a backfill enqueuing thousands moves on to a new action with the same name every 100 jobs; a job run inline there without being enqueued (perform_now) is its own action. A job runs in the action it was enqueued in only within an hour of it. Rake tasks that run a job worker for the life of the process (jobs:work, resque:work, solid_queue:start, good_job:start, …) are left alone; add your own with config.excluded_rake_tasks, or turn the whole grouping off with config.capture_commands = false. Work started on other threads is not grouped.

5. Calls to outside services

A call your app makes to another service is a step of the action that made it: an HTTP request through Net::HTTP (and so Faraday's default adapter, HTTParty, RestClient, the Stripe and Anthropic gems) or the http gem, and an email ActionMailer delivers (SMTP or an API). The action page shows "Created a checkout session at stripe.com · POST /v1/checkout/sessions · 200" or "Sent the “feedback received” email via resend.com"; a failed one reads in the sentence ("…, but the call to slack.com failed").

Sent: the host, the method, the path as a pattern (API versions and a first segment from a fixed list of common collection names such as charges; everything else becomes :id), the status and the time; for an email, its mailer and action. Never a body, a query string, a header, a recipient or a subject. Nothing is recorded outside a request, job or console line, nor for calls to EZLogs itself. Leave a service out with config.excluded_hosts = ["internal.example.com"] (its subdomains too), or stop recording calls with config.capture_outbound = false.

It never slows or blocks the call: the agent reads the clock before and after, and keeps a small record that its own thread turns into an event later. Measured on a local kept-alive connection: about 3 µs per call over the correlation header the agent already adds. The response body is never read, and the app's error is re-raised untouched.


How Correlation Works

Events are automatically linked together using a correlation_id, allowing EZLogs to reconstruct the complete chain of events triggered by a single user action.

Automatic Propagation

HTTP Request
  └─ generates correlation_id: "req_abc123"
     └─ Database Update (inherits: "req_abc123")
     └─ Background Job #1 (inherits: "req_abc123")
        └─ Database Update (inherits: "req_abc123")
        └─ Background Job #2 (inherits: "req_abc123")

Zero configuration required. The agent handles correlation propagation automatically through:

  • Rack request headers
  • Sidekiq job metadata
  • Thread-local storage (within a single request)

Best-Effort Approach

Important: Correlation is best-effort, not guaranteed. Some events may have missing correlation IDs in edge cases:

  • Jobs triggered by cron or external systems
  • Console operations
  • Database callbacks outside request/job context

This is expected and acceptable. EZLogs will still capture these events—they'll just appear as separate, uncorrelated activities.

Design principle: Missing data is acceptable; wrong data is not. The agent never guesses correlation IDs.


Configuration Reference

All options have sensible defaults. Only project_token is required. server_url defaults to ENV["EZLOGS_SERVER_URL"] if set, otherwise https://app.ezlogs.io.

Minimal Configuration

EzLogsAgent.configure do |config|
  config.project_token = "ezl_your_api_key_here"
end

Full Configuration

EzLogsAgent.configure do |config|
  # ==========================================
  # Required Settings
  # ==========================================

  # API Key (get this from your EZLogs dashboard under Install & keys)
  # This is sent as a Bearer token in the Authorization header
  config.project_token = "ezl_your_api_key_here"

  # Server URL (where to send events). Optional: defaults to
  # ENV["EZLOGS_SERVER_URL"] if set, otherwise https://app.ezlogs.io.
  # config.server_url = "https://app.ezlogs.io"

  # ==========================================
  # Event Capture Toggles
  # ==========================================

  # Capture HTTP requests (default: true)
  config.capture_http = true

  # Capture background jobs (default: true)
  config.capture_jobs = true

  # Capture database changes (default: true)
  config.capture_database = true

  # Stamp X-Correlation-ID on outgoing Net::HTTP calls (Faraday, HTTParty,
  # RestClient) and the `http` gem, so another service running an EZLogs agent joins the same
  # action. Incoming calls adopt it only in the agents' own format. Default: true
  config.propagate_correlation = true

  # Record calls to outside services as steps of the action (see "Calls to outside services").
  # Default: true
  config.capture_outbound = true

  # Hosts never recorded, with their subdomains. Default: []
  config.excluded_hosts = []

  # ==========================================
  # Exclusion Lists
  # ==========================================

  # Additional HTTP paths to exclude (with the database writes and job enqueues inside them)
  # Use * suffix for prefix matching (e.g., "/admin*" matches "/admin/users")
  # These are ADDED to the built-in defaults (health checks, assets, etc.)
  config.excluded_paths = ["/admin*", "/internal*", "/api/internal*"]

  # Additional database tables to exclude
  # These are ADDED to the built-in defaults (sessions, schema_migrations, etc.)
  config.excluded_tables = ["audit_logs", "versions", "paper_trail_versions"]

  # Additional job classes to exclude
  # These are ADDED to the built-in defaults (Sidekiq health checks, etc.)
  config.excluded_job_classes = ["MyApp::HealthCheckJob", "MyApp::MetricsJob"]

  # ==========================================
  # Display Names
  # ==========================================

  # Configure how to display human-readable names for database records
  # This affects how action titles appear (e.g., "Updated employee 'Ana Pop'")
  # See "Display Names" section below for details
  config.display_name_for = {
    "Employee" => :full_name, # a method on the model
    "Order" => :reference
  }

  # ==========================================
  # Actor Context
  # ==========================================

  # Configure how to extract the "who" (actor) from requests
  # This is opt-in and highly application-specific
  # See "Actor Context" section below for details
  config.actor_from_request = ->(env, controller) {
    return nil unless controller.respond_to?(:current_user)
    user = controller.current_user
    # Only a signed-in, saved user: a guest object (id 0, never saved) is no one.
    return nil if user.nil? || (user.respond_to?(:persisted?) && !user.persisted?)

    {
      id: user.id.to_s,       # Stable identifier
      label: user.email        # Human-readable display (optional)
    }
  }

  # ==========================================
  # Transport Settings
  # ==========================================

  # Maximum events in memory buffer before oldest are dropped
  # Default: 10000 (approximately 1-2MB of memory)
  # Increased for high-volume workloads with many background jobs
  config.buffer_size = 10000

  # Number of retry attempts for failed sends (with exponential backoff)
  # Default: 3 (retries at 1s, 2s, 4s)
  config.retry_attempts = 3

  # Seconds between automatic buffer flushes
  # Default: 3 (events are sent every 3 seconds if buffer has data)
  # More frequent sends improve throughput for high-volume applications
  config.send_interval = 3

  # ==========================================
  # Logging
  # ==========================================

  # Agent log level
  # Options: :debug, :info, :warn, :error
  # Default: :warn (quiet by default; agent only logs warnings + errors)
  # Set to :debug for verbose output during troubleshooting
  config.log_level = :warn
end

Display Names — Human-Readable Resource Identifiers

A record without a name shows by its short id: "Updated employee #b38a…a236". With display name resolution, it shows by what identifies it to a person: "Updated employee 'Ana Pop'".

Configuration

EzLogsAgent.configure do |config|
  config.display_name_for = {
    "Employee" => :full_name, # "Updated employee 'Ana Pop'"
    "Order" => :reference     # "Created order 'ORD-1042'"
  }
end

Never an email, a phone number, an address, a password, a token or other secret: names show on shared links. From 0.2.24 a personal column (phone, address, …) is never used as a name.

How It Works

When a database callback fires (create, update, delete), the agent resolves a display name:

  1. If configured: Use the specified method (e.g., Order → :reference)
  2. Otherwise, try defaults: name → title → number → label → <model>_number (the same as ezlogs-nextjs and the Supabase install)
  3. If nothing found: EZLogs shows the record by its short id (#123, #b38a…a236)

Examples

Before:

Updated employee #b38a…a236
Deleted order #789

After:

Updated employee 'Ana Pop'
Deleted order 'ORD-2025-0789'

Important Constraints

Only use direct attributes, not associations.

# ✅ GOOD - Direct attribute
config.display_name_for = { "Order" => :reference }

# ❌ BAD - Association (triggers database query)
config.display_name_for = { "Order" => :customer_email }

Why? Associations would trigger additional database queries during event capture, violating the agent's non-blocking guarantee. The display name is resolved using only data already loaded in memory.


Actor Context — Who Triggered This?

EZLogs can track who triggered each action. This adds a human face to your activity log.

Configuration

EzLogsAgent.configure do |config|
  config.actor_from_request = ->(env, controller) {
    # Return nil if controller not available or user not authenticated
    return nil unless controller.respond_to?(:current_user)
    user = controller.current_user
    # Only a signed-in, saved user: a guest object (id 0, never saved) is no one.
    return nil if user.nil? || (user.respond_to?(:persisted?) && !user.persisted?)

    # Return actor hash
    {
      id: user.id.to_s,       # Required: stable identifier
      label: user.email        # Optional: human-readable display
    }
  }
end

Hook Parameters

The hook receives two arguments:

  • env (Hash) — Rack environment hash (always present)
  • controller (Object or nil) — Rails controller instance (nil if not available, e.g., for API-only requests)

Return Value

Return one of:

  • { id: String, label: String } — For identified actors (label is optional)
  • nil — When actor cannot be determined

Schema

Field Type Required Description
id String Yes Stable identifier (e.g., user ID, never changes)
label String No Human-readable display (e.g., email, can change)

Design Philosophy

Actor extraction is opt-in, not automatic. This prevents:

  • Incorrect attribution in impersonation scenarios (admin acting as another user)
  • Wrong actors with service accounts or background jobs
  • Silent failures with custom authentication systems (Devise, Clearance, Authlogic, custom auth)

When actor is unknown, events are captured with actor: null. Missing data is acceptable; wrong data is not.

Examples

With Devise:

config.actor_from_request = ->(env, controller) {
  return nil unless controller.respond_to?(:current_user)
  user = controller.current_user
  # Only a signed-in, saved user: a guest object (id 0, never saved) is no one.
  return nil if user.nil? || (user.respond_to?(:persisted?) && !user.persisted?)

  { id: user.id.to_s, label: user.email }
}

With Rails 8's authentication generator (Current.user):

config.actor_from_request = ->(env, controller) {
  user = Current.user
  return nil if user.nil?

  { id: user.id.to_s, label: user.email_address }
}

A sign-in through it (a new row of sessions) reads "Signed in" without any setup: the agent notes the new session row and never sends it.

With Clearance:

config.actor_from_request = ->(env, controller) {
  return nil unless controller.respond_to?(:current_user)
  user = controller.current_user
  # Only a signed-in, saved user: a guest object (id 0, never saved) is no one.
  return nil if user.nil? || (user.respond_to?(:persisted?) && !user.persisted?)

  { id: user.id.to_s, label: user.email }
}

With Custom Auth:

config.actor_from_request = ->(env, controller) {
  # Extract from session
  user_id = env["rack.session"]&.dig("user_id")
  return nil unless user_id

  # Lookup user (only if you have fast caching)
  user = User.find_by(id: user_id)
  return nil unless user

  { id: user.id.to_s, label: user.email }
}

Safety Guarantees

The agent is designed to be invisible to your application. It will never be the reason your app fails.

Non-Blocking Operation

  • Never raises exceptions to the host application
  • Never blocks HTTP requests or background jobs
  • Sends asynchronously via a background thread
  • Fails gracefully if the server is unreachable

Buffer Overflow Protection

  • Drops oldest events when buffer is full (controlled by buffer_size)
  • Never crashes from memory pressure
  • Logs warnings when buffer approaches capacity

Network Failure Handling

  • Retries with exponential backoff (controlled by retry_attempts)
  • Gives up gracefully after max retries
  • Your application continues normally if EZLogs Server is down

Graceful Shutdown

  • Flushes remaining events when Rails shuts down
  • Waits briefly for final send (non-blocking)
  • Never prevents application shutdown

Design principle: Your application's reliability is more important than capturing every event. EZLogs is best-effort, not guaranteed delivery.


Testing Your Configuration

After installation, verify everything is working:

rails ez_logs_agent:test_connection

What This Command Does

  1. ✅ Validates your configuration (required fields, valid URLs, etc.)
  2. ✅ Tests connectivity to the EZLogs server
  3. ✅ Sends a test event
  4. ✅ Confirms the server accepted it (HTTP 200 response)

Successful Output

🔍 EzLogs Agent Connection Test

Step 1: Validating configuration...
✅ Configuration is valid

Configuration Summary:
  Server URL: https://app.ezlogs.io
  Project Token: ***1a2b
  Capture HTTP: true
  Capture Jobs: true
  Capture Database: true

Step 2: Testing connection to server...
✅ Connection successful (HTTP 200)
   Test event accepted by server

✅ All checks passed! EzLogs Agent is configured correctly.

Failed Output

If the test fails, you'll see exactly what's wrong (excerpt, after the same Step 1 and summary):

Step 2: Testing connection to server...
❌ Authentication failed (HTTP 401)
   Check your project_token in config/initializers/ez_logs_agent.rb

Other failures print one of: ❌ Server endpoint not found (HTTP 404), ❌ Could not resolve host: …, ❌ Connection refused: …, ❌ Connection timeout: …, or ❌ Configuration validation failed: followed by the errors.


Troubleshooting

Quick Diagnosis

Start here. This command catches 90% of configuration issues immediately:

rails ez_logs_agent:test_connection

No Events Showing Up

Symptoms: Your EZLogs dashboard is empty after restarting your application.

Debug steps:

  1. Run the connection test:

    rails ez_logs_agent:test_connection
  2. Check Rails logs for the startup line and for agent errors, e.g. a rejected key:

    [EzLogsAgent] capturing → app.ezlogs.io (key ezl_a1b2c3d4…)
    [EzLogsAgent] [Transport] send failed (401)
    
  3. Enable debug logging in config/initializers/ez_logs_agent.rb:

    config.log_level = :debug

    Then restart Rails. A working agent logs, among others:

    [EzLogsAgent] [Railtie] HTTP capture enabled
    [EzLogsAgent] [Railtie] Agent initialized successfully
    [EzLogsAgent] [Transport] send succeeded (200)
    
  4. Verify network connectivity:

    curl -I https://app.ezlogs.io
  5. Check firewall rules: Ensure your application can reach the EZLogs server on port 443 (HTTPS).


Configuration Validation Errors at Boot

Symptoms: Rails starts but shows warnings from EZLogs Agent.

Example output:

[EzLogsAgent] [Railtie] Configuration validation failed:
[EzLogsAgent] [Railtie]   - project_token is required. Set it in config/initializers/ez_logs_agent.rb
[EzLogsAgent] [Railtie] Agent initialization skipped. Please fix configuration errors.

Solution: Fix the errors listed in the warning message and restart Rails.

Common validation errors:

  • server_url is required. Set it in config/initializers/ez_logs_agent.rb → config.server_url was set to an empty value; remove that line to use the default
  • server_url must be a valid URL (got: …) → Fix the URL format
  • project_token is required. Set it in config/initializers/ez_logs_agent.rb → Set config.project_token

Authentication Errors (HTTP 401)

Symptoms: Connection test or agent logs show HTTP 401.

Debug steps:

  1. Verify your API key:

    • Log into your EZLogs dashboard
    • Go to Install & keys (the menu behind your initials)
    • Copy the active API key
    • Paste it into config.project_token (include the ezl_ prefix)
  2. Check for extra characters:

    # ❌ BAD - Extra quotes or spaces
    config.project_token = " ezl_abc123 "
    
    # ✅ GOOD
    config.project_token = "ezl_abc123"
  3. Ensure the API key is active:

    • Check the EZLogs dashboard to confirm the key hasn't been revoked
    • If revoked, create a new key and update your configuration

Sidekiq Jobs Not Captured

Symptoms: HTTP requests appear in EZLogs but background jobs don't.

Debug steps:

  1. Verify Sidekiq is running:

    # Should show running Sidekiq processes
    ps aux | grep sidekiq
  2. Check agent configuration:

    # Ensure jobs capture is enabled (this is the default)
    config.capture_jobs = true
  3. Look for Sidekiq registration in logs:

    [EzLogsAgent] [Railtie] Sidekiq server middleware registered
    

    Note: This message only appears in Sidekiq worker processes, not web processes.

  4. Verify job classes aren't excluded: Check config.excluded_job_classes to ensure your jobs aren't being filtered out.

  5. Run a test job:

    # In Rails console
    class TestJob < ApplicationJob
      def perform
        Rails.logger.info "Test job executed"
      end
    end
    
    TestJob.perform_later

    Check your EZLogs dashboard for the job execution.


Database Events Missing

Symptoms: HTTP requests and jobs appear, but database changes don't.

Debug steps:

  1. Verify ActiveRecord is present:

    # In Rails console
    defined?(ActiveRecord)  # Should return "constant"
  2. Check agent configuration:

    # Ensure database capture is enabled (this is the default)
    config.capture_database = true
  3. Look for database capture registration in logs:

    [EzLogsAgent] [Railtie] Database capture installed (per-row + bulk)
    
  4. Verify models aren't excluded: Check config.excluded_tables to ensure your tables aren't being filtered out.

  5. What is and isn't captured:

    • ✅ User.create(...) — Captured (per-row callback)
    • ✅ user.update(...) — Captured (per-row callback)
    • ✅ user.destroy — Captured (per-row callback)
    • ✅ User.update_all(...) — Captured as a bulk_database event (filter + SET clause + row count; no per-row IDs)
    • ✅ User.where(...).delete_all — Captured as a bulk_database event
    • ✅ User.insert_all(...) / upsert_all(...) — Captured (columns + count)
    • ❌ User.find(...) — NOT captured (read-only)
    • ❌ User.connection.execute("DELETE FROM ...") — NOT captured (raw SQL bypasses the typed AR API we hook)

Events Appearing Late

Symptoms: Events show up in your dashboard with a delay.

This is normal. Events are sent in batches every 3 seconds by default.

To reduce latency further (at the cost of more network requests):

# Send events every 1-2 seconds instead of 3
config.send_interval = 1

Note: Even with send_interval = 2, there's still processing time on the server. Real-time is not guaranteed.


Correlation IDs Missing

Symptoms: Events appear as separate activities instead of being grouped together.

This is expected in some scenarios:

  • Jobs triggered by cron or external systems
  • Console operations (rails console)
  • Database callbacks outside request/job context
  • Cross-process job chains (e.g., Job A in Process 1 enqueues Job B in Process 2)

This is normal and acceptable. Correlation is best-effort, not guaranteed.

If correlation is missing when it should be present:

  1. Enable debug logging: config.log_level = :debug
  2. Check that jobs are enqueued within the same request context

Performance Impact

Symptoms: Concerned about memory usage or application performance.

The agent is designed to be lightweight:

  • Memory: ~1-2MB for default buffer (10,000 events)
  • CPU: Negligible (background thread does all work)
  • Latency: Zero added to requests (capture is asynchronous)

If you experience issues:

  1. Reduce buffer size (for low-volume apps):

    # Reduce from 10000 to 5000 events
    config.buffer_size = 5000
  2. Increase send interval (events sent less frequently):

    # Send every 5-10 seconds instead of 3
    config.send_interval = 5
  3. Disable specific capture types:

    # Database changes can be noisy in write-heavy apps
    config.capture_database = false

Understanding Agent Log Messages

Normal operation (the startup line always shows; the other two only at config.log_level = :debug):

[EzLogsAgent] capturing → app.ezlogs.io (key ezl_a1b2c3d4…)
[EzLogsAgent] [Railtie] Agent initialized successfully
[EzLogsAgent] [Transport] send succeeded (200)

Warnings:

[EzLogsAgent] [Buffer] Buffer full (10000), dropped oldest event
→ Your app produces events faster than they are sent
→ Increase buffer_size or lower send_interval

Errors (need attention):

[EzLogsAgent] [Transport] send failed (401)
→ Invalid or revoked API key, check config.project_token

[EzLogsAgent] [Transport] send failed: Net::OpenTimeout - execution expired
→ Network issue or the server is down; the batch is retried (retry_attempts)

[EzLogsAgent] [RetrySender] Failed after 4 attempts, dropping 12 events
→ All retries failed; those events are lost

[EzLogsAgent] [Railtie] Configuration validation failed:
→ Fix configuration errors and restart Rails

Getting Help

If you're still stuck after trying the above:

  1. Check GitHub Issues: github.com/dezsirazvan/ez_logs_agent/issues
  2. Open a new issue with:
    • Rails version and Ruby version
    • Relevant logs (set config.log_level = :debug)
    • Output of rails ez_logs_agent:test_connection
    • Steps to reproduce the problem

How It Works

A visual overview of the agent's architecture:

Your Rails Application
       │
       ├─ HTTP Request arrives
       │     └─ Rack middleware captures event
       │             └─ Adds to Buffer
       │
       ├─ Background Job runs
       │     └─ Sidekiq middleware captures event
       │             └─ Adds to Buffer
       │
       └─ Database record changes
             └─ ActiveRecord callback captures event
                     └─ Adds to Buffer

                            │
                            ▼
                    ┌───────────────┐
                    │    Buffer     │  (thread-safe, in-memory, circular)
                    │ 10,000 events │
                    └───────────────┘
                            │
                            ▼
                    ┌───────────────┐
                    │FlushScheduler │  (background thread, every 3s)
                    └───────────────┘
                            │
                            ▼
                    ┌───────────────┐
                    │   Transport   │  (HTTP POST with retry logic)
                    │               │  (Authorization: Bearer token)
                    └───────────────┘
                            │
                            ▼
                    ┌───────────────┐
                    │ EZLogs Server │  (groups events into stories)
                    └───────────────┘

Key points:

  • Capture happens synchronously (microseconds, no blocking)
  • Sending happens asynchronously (background thread)
  • Buffer is circular (oldest events dropped when full)
  • Transport uses exponential backoff (1s, 2s, 4s retries)

Development

Running Tests

cd ez_logs_agent
bundle install
bundle exec rspec

Test Coverage

786+ tests covering:

  • HTTP request capture
  • GraphQL support
  • Background job capture (Sidekiq + ActiveJob)
  • Database callbacks (create, update, destroy)
  • Correlation propagation
  • Actor context extraction
  • Display name resolution
  • Buffer overflow handling
  • Transport retry logic
  • Configuration validation

License

MIT License. See LICENSE.txt for details.


Contributing

We welcome bug reports and pull requests!

To report a bug:

  1. Check existing GitHub Issues
  2. Open a new issue with reproduction steps

To contribute code:

  1. Fork the repository
  2. Create a feature branch
  3. Write tests for your changes
  4. Ensure all tests pass: bundle exec rspec
  5. Submit a pull request with a clear description

Code style:

  • Follow the existing Ruby style
  • Write descriptive commit messages
  • Update documentation for user-facing changes

Status

  • 786 tests, all green
  • Wire-format parity-tested against the Next.js agent's fixtures (every event shape byte-for-byte identical)
  • Production-shipping in multiple Rails apps including our Bookhouse demo app (Rails 8 + Sidekiq + Devise, exercises every capture path)

Support


Made with clarity in mind. Built for everyone on your team, not just engineers.