Skip to content

Commit 91811b6

Browse files
authored
feat(logs): document structured logging in Rails (#14844)
Adds detailed docs about Structured Logging setup in Rails that was added in sentry-rails 5.27.0. ## Preview https://sentry-docs-git-ruby-extend-rails-structured-logging-section.sentry.dev/platforms/ruby/guides/rails/logs/ ## IS YOUR CHANGE URGENT? Help us prioritize incoming PRs by letting us know when the change needs to go live. - [x] Urgent deadline (GA date, etc.): Logs are already GA so would be great to get this in fast 🙏🏻 - [ ] Other deadline: <!-- ENTER DATE HERE --> - [ ] None: Not urgent, can wait up to 1 week+ ## SLA - Teamwork makes the dream work, so please add a reviewer to your PRs. - Please give the docs team up to 1 week to review your PR unless you've added an urgent due date to it. Thanks in advance for your help! ## PRE-MERGE CHECKLIST *Make sure you've checked the following before merging your changes:* - [ ] Checked Vercel preview for correctness, including links - [ ] PR was reviewed and approved by any necessary SMEs (subject matter experts) - [ ] PR was reviewed and approved by a member of the [Sentry docs team](https://github.com/orgs/getsentry/teams/docs) ## LEGAL BOILERPLATE <!-- Sentry employees and contractors can delete or ignore this section. --> Look, I get it. The entity doing business as "Sentry" was incorporated in the State of Delaware in 2015 as Functional Software, Inc. and is gonna need some rights from me in order to utilize my contributions in this here PR. So here's the deal: I retain all rights, title and interest in and to my contributions, and by keeping this boilerplate intact I confirm that Sentry can use, modify, copy, and redistribute my contributions, under Sentry's choice of terms. ## EXTRA RESOURCES - [Sentry Docs contributor guide](https://docs.sentry.io/contributing/)
1 parent 7a09e90 commit 91811b6

File tree

8 files changed

+373
-10
lines changed

8 files changed

+373
-10
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
title: Set Up Logs
3+
sidebar_title: Logs
4+
description: "Structured logs allow you to send, view and query logs sent from your Rails applications within Sentry."
5+
sidebar_order: 5600
6+
---
7+
8+
With Sentry Structured Logs, you can send text-based log information from your Rails applications to Sentry. Once in Sentry, these logs can be viewed alongside relevant errors, searched by text-string, or searched using their individual attributes.
9+
10+
## Requirements
11+
12+
<PlatformContent includePath="logs/requirements" />
13+
14+
## Setup
15+
16+
<PlatformContent includePath="logs/setup" />
17+
18+
## Usage
19+
20+
<PlatformContent includePath="logs/usage" />
21+
22+
## Options
23+
24+
<PlatformContent includePath="logs/options" />
25+
26+
## Default Attributes
27+
28+
<PlatformContent includePath="logs/default-attributes" />

docs/product/explore/logs/getting-started/index.mdx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,11 @@ To set up Sentry Logs, use the links below for supported SDKs. After it's been s
241241
label="Ruby"
242242
url="/platforms/ruby/logs/"
243243
/>
244+
- <LinkWithPlatformIcon
245+
platform="ruby.rails"
246+
label="Rails"
247+
url="/platforms/ruby/guides/rails/logs/"
248+
/>
244249

245250
### Go
246251

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
The Rails SDK automatically sets several default attributes on all log entries to provide context and improve debugging:
2+
3+
<Include name="logs/default-attributes/core" />
4+
5+
<Include name="logs/default-attributes/message-template" />
6+
7+
<Include name="logs/default-attributes/server" />
8+
9+
<Include name="logs/default-attributes/user" />
10+
11+
<Include name="logs/default-attributes/integration" />
12+
13+
### Rails-Specific Attributes
14+
15+
When using structured logging with Log Subscribers, additional Rails-specific attributes are automatically included:
16+
17+
#### ActiveRecord Logs
18+
- `sql` - The SQL query executed
19+
- `duration_ms` - Query execution time in milliseconds
20+
- `cached` - Whether the query result was cached
21+
- `statement_name` - SQL statement name (when available and not "SQL")
22+
- `connection_id` - Database connection identifier (when available)
23+
- `db_system` - Database adapter (e.g., "postgresql", "mysql2", "sqlite3")
24+
- `db_name` - Database name (sanitized for SQLite file paths)
25+
- `server_address` - Database host (when available)
26+
- `server_port` - Database port (when available)
27+
- `server_socket_address` - Database socket path (when available)
28+
29+
#### ActionController Logs
30+
- `controller` - Controller class name
31+
- `action` - Action method name
32+
- `duration_ms` - Request processing time in milliseconds
33+
- `method` - HTTP request method
34+
- `path` - Request path
35+
- `format` - Response format (html, json, etc.)
36+
- `status` - HTTP response status code (when available)
37+
- `view_runtime_ms` - View rendering time in milliseconds (when available)
38+
- `db_runtime_ms` - Database query time in milliseconds (when available)
39+
- `params` - Filtered request parameters (only when `send_default_pii` is enabled)
40+
41+
#### ActiveJob Logs (when enabled)
42+
43+
**Common attributes for all ActiveJob events:**
44+
- `job_class` - Job class name
45+
- `job_id` - Unique job identifier
46+
- `queue_name` - Queue name where job is processed
47+
- `executions` - Number of execution attempts
48+
- `priority` - Job priority
49+
50+
**For `perform` events:**
51+
- `duration_ms` - Job execution time in milliseconds
52+
- `adapter` - Queue adapter class name
53+
- `scheduled_at` - When job was scheduled in ISO8601 format (for delayed jobs)
54+
- `delay_ms` - Delay between scheduling and execution in milliseconds (for delayed jobs)
55+
- `arguments` - Job arguments (only when `send_default_pii` is enabled, filtered for sensitive data)
56+
57+
**For `enqueue` events:**
58+
- `adapter` - Queue adapter class name (when available)
59+
- `scheduled_at` - When job was scheduled in ISO8601 format (for delayed jobs)
60+
- `delay_seconds` - Delay between current time and scheduled time in seconds (for delayed jobs)
61+
62+
**For `retry_stopped` and `discard` events:**
63+
- `error_class` - Error class name (when error is present)
64+
- `error_message` - Error message (when error is present)
65+
66+
#### ActionMailer Logs (when enabled)
67+
68+
**For `deliver` events:**
69+
- `mailer` - Mailer class name
70+
- `duration_ms` - Email delivery time in milliseconds
71+
- `perform_deliveries` - Whether deliveries are enabled
72+
- `delivery_method` - Email delivery method used (when available)
73+
- `date` - Email date header as string (when available)
74+
- `message_id` - Email message ID (only when `send_default_pii` is enabled)
75+
76+
**For `process` events:**
77+
- `mailer` - Mailer class name
78+
- `action` - Mailer action method name
79+
- `duration_ms` - Email processing time in milliseconds
80+
- `params` - Mailer parameters (only when `send_default_pii` is enabled, filtered for sensitive data)

platform-includes/logs/integrations/ruby.mdx

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,4 @@ logger.error("Hello from stdlib logger")
2222
Ruby's stdlib logger does not support structured logging, that's why logs are sent to Sentry as plain messages with default attributes added automatically by the SDK.
2323
</Alert>
2424

25-
## Ruby on Rails
2625

27-
If you enable `:logger` patch like explained above, this will affect Rails' built-in logger. This means that anything that Rails logs, and any custom usage of the Rails logger, will result in sending log entries to Sentry, for example:
28-
29-
```ruby
30-
# All these calls will result in log entries in Sentry
31-
# if :logger patch is enabled
32-
Rails.logger.debug("Hello from Rails logger")
33-
Rails.logger.info("Hello from Rails logger")
34-
Rails.logger.error("Hello from Rails logger")
35-
```
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
### Available Built-in Subscribers
2+
3+
The Rails SDK includes several built-in log subscribers that you can enable:
4+
5+
#### Default Subscribers (enabled automatically)
6+
- **ActiveRecord**: Database queries with SQL, duration, connection info, and caching status
7+
- **ActionController**: HTTP requests with controller, action, parameters, response status, and timing
8+
9+
#### Additional Subscribers (opt-in)
10+
- **ActiveJob**: Background job execution (`perform`), enqueueing (`enqueue`), retry failures (`retry_stopped`), and job discarding (`discard`)
11+
- **ActionMailer**: Email delivery (`deliver`) and processing (`process`) events
12+
13+
### Custom Subscriber Configuration
14+
15+
You can customize which subscribers are active:
16+
17+
```ruby
18+
Sentry.init do |config|
19+
config.dsn = "___PUBLIC_DSN___"
20+
21+
config.enable_logs = true
22+
23+
config.rails.structured_logging.enabled = true
24+
25+
config.rails.structured_logging.subscribers = {
26+
active_record: Sentry::Rails::LogSubscribers::ActiveRecordSubscriber,
27+
action_controller: Sentry::Rails::LogSubscribers::ActionControllerSubscriber
28+
}
29+
end
30+
```
31+
32+
To enable additional subscribers, add them to the configuration:
33+
34+
```ruby
35+
Sentry.init do |config|
36+
config.dsn = "___PUBLIC_DSN___"
37+
38+
config.enable_logs = true
39+
40+
config.rails.structured_logging.enabled = true
41+
42+
config.rails.structured_logging.subscribers = {
43+
active_record: Sentry::Rails::LogSubscribers::ActiveRecordSubscriber,
44+
action_controller: Sentry::Rails::LogSubscribers::ActionControllerSubscriber,
45+
active_job: Sentry::Rails::LogSubscribers::ActiveJobSubscriber,
46+
action_mailer: Sentry::Rails::LogSubscribers::ActionMailerSubscriber
47+
}
48+
end
49+
```
50+
51+
To disable specific subscribers:
52+
53+
```ruby
54+
Sentry.init do |config|
55+
config.dsn = "___PUBLIC_DSN___"
56+
57+
config.enable_logs = true
58+
59+
config.rails.structured_logging.enabled = true
60+
61+
config.rails.structured_logging.subscribers = {
62+
active_record: Sentry::Rails::LogSubscribers::ActiveRecordSubscriber
63+
# ActionController subscriber disabled
64+
}
65+
end
66+
```
67+
68+
### Creating Custom Log Subscribers
69+
70+
You can create custom log subscribers by extending the base class:
71+
72+
```ruby
73+
class MyCustomSubscriber < Sentry::Rails::LogSubscriber
74+
# Attach to your component's instrumentation events
75+
attach_to :my_component
76+
77+
def my_event(event)
78+
log_structured_event(
79+
message: "Custom event occurred",
80+
level: :info,
81+
attributes: {
82+
duration_ms: event.duration,
83+
custom_data: event.payload[:custom_data],
84+
user_id: event.payload[:user_id]
85+
}
86+
)
87+
end
88+
89+
def another_event(event)
90+
log_structured_event(
91+
message: "Another custom event",
92+
level: :warn,
93+
attributes: {
94+
event_type: event.payload[:type],
95+
metadata: event.payload[:metadata]
96+
}
97+
)
98+
end
99+
end
100+
```
101+
102+
Then register your custom subscriber:
103+
104+
```ruby
105+
Sentry.init do |config|
106+
config.dsn = "___PUBLIC_DSN___"
107+
108+
config.enable_logs = true
109+
110+
config.rails.structured_logging.enabled = true
111+
112+
config.rails.structured_logging.subscribers = {
113+
active_record: Sentry::Rails::LogSubscribers::ActiveRecordSubscriber,
114+
action_controller: Sentry::Rails::LogSubscribers::ActionControllerSubscriber,
115+
my_component: MyCustomSubscriber
116+
}
117+
end
118+
```
119+
120+
### Sensitive Data Filtering
121+
122+
Log subscribers automatically respect Rails' parameter filtering configuration. Sensitive parameters defined in `config.filter_parameters` will be filtered from structured logs:
123+
124+
```ruby
125+
# config/application.rb
126+
config.filter_parameters += [:password, :credit_card, :ssn]
127+
```
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
Logs for Rails are supported in Sentry Rails SDK version `5.27.0` and above.
2+
3+
```bash
4+
gem install sentry-rails
5+
```
6+
7+
Or add it to your Gemfile:
8+
9+
```ruby
10+
gem "sentry-rails"
11+
```
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
To enable logging, you need to initialize the SDK with the `enable_logs` option set to `true`.
2+
3+
```ruby
4+
Sentry.init do |config|
5+
config.dsn = "___PUBLIC_DSN___"
6+
config.enable_logs = true
7+
end
8+
```
9+
10+
### Structured Logging with Log Subscribers
11+
12+
<Alert level="info" title="Note on structured logging">
13+
Structured logging with Log Subscribers provides rich context and metadata compared to plain logger messages. This enables better filtering, searching, and analysis of your application's behavior in Sentry.
14+
</Alert>
15+
16+
Rails applications can benefit from structured logging using ActiveSupport's Log Subscribers. This feature captures Rails instrumentation events and sends them as structured logs to Sentry with relevant context and metadata.
17+
18+
#### Default Setup
19+
20+
To enable structured logging with default subscribers:
21+
22+
```ruby
23+
Sentry.init do |config|
24+
config.dsn = "___PUBLIC_DSN___"
25+
config.enable_logs = true
26+
config.rails.structured_logging.enabled = true
27+
end
28+
```
29+
30+
By default, this enables structured logging for:
31+
32+
- **ActiveRecord**: Database queries with SQL, duration, connection info, and caching status
33+
- **ActionController**: HTTP requests with controller, action, parameters, response status, and timing
34+
35+
Additional subscribers are available but not enabled by default:
36+
37+
- **ActiveJob**: Background job execution (`perform`), enqueueing (`enqueue`), retry failures (`retry_stopped`), and job discarding (`discard`)
38+
- **ActionMailer**: Email delivery (`deliver`) and processing (`process`) events
39+
40+
See the [Options](#options) section for information on how to enable additional subscribers.
41+
42+
### Basic Rails Logger Integration
43+
44+
If you enable `:logger` patch, this will affect Rails' built-in logger. This means that anything that Rails logs, and any custom usage of the Rails logger, will result in sending log entries to Sentry:
45+
46+
```ruby
47+
Sentry.init do |config|
48+
config.dsn = "___PUBLIC_DSN___"
49+
config.enable_logs = true
50+
config.enabled_patches = [:logger]
51+
end
52+
```
53+
54+
Then all logs from Rails logger will be sent to Sentry, for example:
55+
56+
```ruby
57+
# All these calls will result in log entries in Sentry
58+
# if :logger patch is enabled
59+
Rails.logger.debug("Hello from Rails logger")
60+
Rails.logger.info("Hello from Rails logger")
61+
Rails.logger.error("Hello from Rails logger")
62+
```
63+
64+
<Alert level="warning" title="Note on logger patch">
65+
Enabling `:logger` patch will send all logs from Rails logger to Sentry. This includes logs from Rails framework itself, which might not be desired. In that case we recommend using [Sentry logger](#using-sentry-logger) or [structured logging with log subscribers](#structured-logging-with-log-subscribers).
66+
</Alert>

0 commit comments

Comments
 (0)