-
-
Notifications
You must be signed in to change notification settings - Fork 515
Rails active support log subscribers #2690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
solnic
wants to merge
20
commits into
master
Choose a base branch
from
2605-rails-active-support-log-subscribers
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
e70ac03
Better warning in Sentry.logger
solnic 497171a
Add DebugStructuredLogger
solnic f5ebedb
[rails] introduce abstract log subscriber
solnic af61e02
[rails] add structured logging config/activation
solnic 8ede8d9
[rails] add ActionController log subscriber
solnic 4c630fe
[rails] add ActiveRecord log subscriber
solnic d5eae11
[rails] add ActiveJob log subscriber
solnic 338ef6c
[rails] add ActionMailer log subscriber
solnic ce7e3ef
[rails] add e2e specs for rails structured logging
solnic 0ac5022
[rails] move specs
solnic cf91d44
[rails] add requires
solnic be03827
Update CHANGELOG
solnic 1c63745
Simplify config
solnic 0256acc
Fix debug transport clean up
solnic 1424ecd
Skip including db attributes if connection is not in the payload
solnic 352385c
Fix handling of duration
solnic 741eea3
Set action controller and active record as default log subscribers
solnic 2a78399
Update CHANGELOG
solnic 7ff156a
Use duration_ms helper
solnic 01ae4cb
Clean up specs organization
solnic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
# frozen_string_literal: true | ||
|
||
require "active_support/log_subscriber" | ||
|
||
module Sentry | ||
module Rails | ||
# Base class for Sentry log subscribers that extends ActiveSupport::LogSubscriber | ||
# to provide structured logging capabilities for Rails components. | ||
# | ||
# This class follows Rails' LogSubscriber pattern and provides common functionality | ||
# for capturing Rails instrumentation events and logging them through Sentry's | ||
# structured logging system. | ||
# | ||
# @example Creating a custom log subscriber | ||
# class MySubscriber < Sentry::Rails::LogSubscriber | ||
# attach_to :my_component | ||
# | ||
# def my_event(event) | ||
# log_structured_event( | ||
# message: "My event occurred", | ||
# level: :info, | ||
# attributes: { | ||
# duration_ms: event.duration, | ||
# custom_data: event.payload[:custom_data] | ||
# } | ||
# ) | ||
# end | ||
# end | ||
class LogSubscriber < ActiveSupport::LogSubscriber | ||
class << self | ||
if ::Rails.version.to_f < 6.0 | ||
# Rails 5.x does not provide detach_from | ||
def detach_from(namespace, notifications = ActiveSupport::Notifications) | ||
listeners = public_instance_methods(false) | ||
.flat_map { |key| | ||
notifications.notifier.listeners_for("#{key}.#{namespace}") | ||
} | ||
.select { |listener| listener.instance_variable_get(:@delegate).is_a?(self) } | ||
|
||
listeners.map do |listener| | ||
notifications.notifier.unsubscribe(listener) | ||
end | ||
end | ||
end | ||
end | ||
|
||
protected | ||
|
||
# Log a structured event using Sentry's structured logger | ||
# | ||
# @param message [String] The log message | ||
# @param level [Symbol] The log level (:trace, :debug, :info, :warn, :error, :fatal) | ||
# @param attributes [Hash] Additional structured attributes to include | ||
def log_structured_event(message:, level: :info, attributes: {}) | ||
Sentry.logger.public_send(level, message, **attributes) | ||
rescue => e | ||
# Silently handle any errors in logging to avoid breaking the application | ||
Sentry.configuration.sdk_logger.debug("Failed to log structured event: #{e.message}") | ||
end | ||
|
||
# Calculate duration in milliseconds from an event | ||
# | ||
# @param event [ActiveSupport::Notifications::Event] The event | ||
# @return [Float] Duration in milliseconds | ||
def duration_ms(event) | ||
event.duration.round(2) | ||
end | ||
end | ||
end | ||
end |
113 changes: 113 additions & 0 deletions
113
sentry-rails/lib/sentry/rails/log_subscribers/action_controller_subscriber.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
# frozen_string_literal: true | ||
|
||
require "sentry/rails/log_subscriber" | ||
require "sentry/rails/log_subscribers/parameter_filter" | ||
|
||
module Sentry | ||
module Rails | ||
module LogSubscribers | ||
# LogSubscriber for ActionController events that captures HTTP request processing | ||
# and logs them using Sentry's structured logging system. | ||
# | ||
# This subscriber captures process_action.action_controller events and formats them | ||
# with relevant request information including controller, action, HTTP status, | ||
# request parameters, and performance metrics. | ||
# | ||
# @example Usage | ||
# # Enable structured logging for ActionController | ||
# Sentry.init do |config| | ||
# config.enable_logs = true | ||
# config.rails.structured_logging = true | ||
# config.rails.structured_logging.subscribers = { action_controller: Sentry::Rails::LogSubscribers::ActionControllerSubscriber } | ||
# end | ||
class ActionControllerSubscriber < Sentry::Rails::LogSubscriber | ||
include ParameterFilter | ||
|
||
# Handle process_action.action_controller events | ||
# | ||
# @param event [ActiveSupport::Notifications::Event] The controller action event | ||
def process_action(event) | ||
payload = event.payload | ||
|
||
controller = payload[:controller] | ||
action = payload[:action] | ||
|
||
status = extract_status(payload) | ||
|
||
attributes = { | ||
controller: controller, | ||
action: action, | ||
status: status, | ||
duration_ms: duration_ms(event), | ||
method: payload[:method], | ||
path: payload[:path], | ||
format: payload[:format] | ||
} | ||
|
||
if payload[:view_runtime] | ||
attributes[:view_runtime_ms] = payload[:view_runtime].round(2) | ||
end | ||
|
||
if payload[:db_runtime] | ||
attributes[:db_runtime_ms] = payload[:db_runtime].round(2) | ||
end | ||
|
||
if Sentry.configuration.send_default_pii && payload[:params] | ||
filtered_params = filter_sensitive_params(payload[:params]) | ||
attributes[:params] = filtered_params unless filtered_params.empty? | ||
end | ||
|
||
level = level_for_request(payload) | ||
message = "#{controller}##{action}" | ||
|
||
log_structured_event( | ||
message: message, | ||
level: level, | ||
attributes: attributes | ||
) | ||
end | ||
|
||
private | ||
|
||
def extract_status(payload) | ||
if payload[:status] | ||
payload[:status] | ||
elsif payload[:exception] | ||
case payload[:exception].first | ||
when "ActionController::RoutingError" | ||
404 | ||
when "ActionController::BadRequest" | ||
400 | ||
else | ||
500 | ||
end | ||
end | ||
end | ||
|
||
def level_for_request(payload) | ||
status = payload[:status] | ||
|
||
# In Rails < 6.0 status is not set when an action raised an exception | ||
if status.nil? && payload[:exception] | ||
case payload[:exception].first | ||
when "ActionController::RoutingError" | ||
:warn | ||
when "ActionController::BadRequest" | ||
:warn | ||
else | ||
:error | ||
end | ||
elsif status >= 200 && status < 400 | ||
:info | ||
elsif status >= 400 && status < 500 | ||
:warn | ||
elsif status >= 500 | ||
:error | ||
else | ||
:info | ||
end | ||
end | ||
end | ||
end | ||
end | ||
end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.