posthog-rails 3.22.0 → 3.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/lib/generators/posthog/templates/posthog.rb +18 -1
- data/lib/posthog/rails/action_cable.rb +23 -11
- data/lib/posthog/rails/active_job.rb +63 -3
- data/lib/posthog/rails/capture_exceptions.rb +4 -94
- data/lib/posthog/rails/configuration.rb +11 -0
- data/lib/posthog/rails/controller_helpers.rb +33 -0
- data/lib/posthog/rails/error_subscriber.rb +30 -1
- data/lib/posthog/rails/exception_context.rb +155 -0
- data/lib/posthog/rails/logs/appender.rb +9 -3
- data/lib/posthog/rails/logs/notifications.rb +293 -0
- data/lib/posthog/rails/logs/setup.rb +5 -0
- data/lib/posthog/rails/railtie.rb +36 -0
- data/lib/posthog/rails/streaming_exceptions.rb +3 -2
- data/lib/posthog/rails/version.rb +1 -1
- data/lib/posthog/rails.rb +1 -0
- metadata +4 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: fe991353ced9e95b77ef50aaadbfd2425ccd0cde6c0b306101d1d68b132690cf
|
|
4
|
+
data.tar.gz: 8f511758988ef33f46932212dbf70aadf4c637832a3963a71ad75f8cddb8ceec
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: d33e6c620adbefe406a91f3573577b0c924d635ad5b962cf7a87272867027099874e1814f281c7e8dedaec13ce4131ff09241f734478aee0124a3af34c3d119c
|
|
7
|
+
data.tar.gz: d29ebcec8d4df442380ef5feb1a670c0dd1d3c6af27412685c80790b6a7c34faeb7c23297f3b7386b9db12665301a5cb03c9f8ebbd2a2986897cc6b1cfe318cd
|
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
# These settings control how PostHog integrates with Rails features.
|
|
11
11
|
|
|
12
12
|
PostHog::Rails.configure do |config|
|
|
13
|
-
# Automatically capture exceptions (default: false)
|
|
13
|
+
# Automatically capture exceptions, including terminating rails runner failures (default: false)
|
|
14
|
+
# Successful runner exits are ignored; failures are captured before SDK shutdown
|
|
14
15
|
# Includes Action Cable connect/disconnect, channel subscribe/unsubscribe, and channel actions.
|
|
15
16
|
# config.auto_capture_exceptions = true
|
|
16
17
|
|
|
@@ -22,6 +23,10 @@ PostHog::Rails.configure do |config|
|
|
|
22
23
|
# Set to true to enable automatic ActiveJob exception tracking
|
|
23
24
|
# config.auto_instrument_active_job = true
|
|
24
25
|
|
|
26
|
+
# Report failures when Active Job schedules a retry (default: false)
|
|
27
|
+
# Requires auto_instrument_active_job; terminal unhandled failures are already reported.
|
|
28
|
+
# config.report_active_job_retries = true
|
|
29
|
+
|
|
25
30
|
# Use PostHog tracing headers for request-scoped identity/session context (default: true)
|
|
26
31
|
# Request metadata (current URL, method, path, user agent, and IP) is always captured during Rails requests
|
|
27
32
|
# Set to false to ignore client-supplied X-PostHog-Distinct-Id and X-PostHog-Session-Id headers
|
|
@@ -70,6 +75,18 @@ PostHog::Rails.configure do |config|
|
|
|
70
75
|
# Broadcast Rails.logger into PostHog Logs (default: true when logs enabled)
|
|
71
76
|
# config.logs_forward_rails_logger = true
|
|
72
77
|
|
|
78
|
+
# Structured notification logs (default: []; requires logs_enabled).
|
|
79
|
+
# Select only installed components; this does not load optional Rails components.
|
|
80
|
+
# Set logs_forward_rails_logger = false to avoid also forwarding generic log lines.
|
|
81
|
+
# config.logs_notifications = [:action_controller, :active_record, :active_job, :action_mailer]
|
|
82
|
+
# SQL records are debug; other successful lifecycle events are info, failures error.
|
|
83
|
+
# Controller params and keyed job arguments respect Rails filter_parameters and
|
|
84
|
+
# are JSON strings in rails.params / rails.job.arguments (bounded to 10 KB).
|
|
85
|
+
# Custom filters see original key/value types; unsafe or oversized parameter
|
|
86
|
+
# trees are redacted as a whole, not truncated before filtering.
|
|
87
|
+
# Unkeyed job arguments are redacted. SQL text/binds, headers/cookies, mail
|
|
88
|
+
# recipients, subject and content are not collected by notification logging.
|
|
89
|
+
|
|
73
90
|
# Minimum severity to forward; nil inherits Rails.logger's level (default: nil)
|
|
74
91
|
# config.logs_level = :info
|
|
75
92
|
|
|
@@ -6,8 +6,29 @@ require 'posthog/rails/request_metadata'
|
|
|
6
6
|
|
|
7
7
|
module PostHog
|
|
8
8
|
module Rails
|
|
9
|
+
# @api private
|
|
10
|
+
class ActionCableExceptionContext < ExceptionContext
|
|
11
|
+
def initialize(request, connection)
|
|
12
|
+
super(request)
|
|
13
|
+
@connection = connection
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
private
|
|
17
|
+
|
|
18
|
+
def extract_current_user(controller)
|
|
19
|
+
return super if controller
|
|
20
|
+
|
|
21
|
+
method_name = PostHog::Rails.config&.current_user_method || :current_user
|
|
22
|
+
@connection.send(method_name) if @connection.respond_to?(method_name, true)
|
|
23
|
+
rescue StandardError
|
|
24
|
+
nil
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
|
|
9
28
|
# @api private
|
|
10
29
|
class ActionCableCapture < CaptureExceptions
|
|
30
|
+
include ParameterFilter
|
|
31
|
+
|
|
11
32
|
def initialize(connection, operation, channel: nil, data: nil)
|
|
12
33
|
super(nil)
|
|
13
34
|
@connection = connection
|
|
@@ -76,16 +97,7 @@ module PostHog
|
|
|
76
97
|
end
|
|
77
98
|
|
|
78
99
|
def extract_distinct_id(env)
|
|
79
|
-
|
|
80
|
-
rescue StandardError
|
|
81
|
-
nil
|
|
82
|
-
end
|
|
83
|
-
|
|
84
|
-
def extract_current_user(controller)
|
|
85
|
-
return super if controller
|
|
86
|
-
|
|
87
|
-
method_name = PostHog::Rails.config&.current_user_method || :current_user
|
|
88
|
-
@connection.send(method_name) if @connection.respond_to?(method_name, true)
|
|
100
|
+
ActionCableExceptionContext.new(ActionDispatch::Request.new(env), @connection).distinct_id
|
|
89
101
|
rescue StandardError
|
|
90
102
|
nil
|
|
91
103
|
end
|
|
@@ -213,7 +225,7 @@ module PostHog
|
|
|
213
225
|
end
|
|
214
226
|
end
|
|
215
227
|
|
|
216
|
-
private_constant :ActionCableCapture, :ActionCableContext,
|
|
228
|
+
private_constant :ActionCableExceptionContext, :ActionCableCapture, :ActionCableContext,
|
|
217
229
|
:ActionCableConnectionExtensions, :ActionCableChannelExtensions,
|
|
218
230
|
:ActionCableDispatch, :ActionCableSubscriptionsExtensions
|
|
219
231
|
end
|
|
@@ -13,7 +13,33 @@ module PostHog
|
|
|
13
13
|
def self.prepended(base)
|
|
14
14
|
base.extend(ClassMethods)
|
|
15
15
|
base.around_perform :with_posthog_job_context, prepend: true if base.respond_to?(:around_perform)
|
|
16
|
+
base.prepend(LegacyRetryReporting) if ::ActiveJob::VERSION::MAJOR < 6
|
|
17
|
+
return if @retry_subscription
|
|
18
|
+
|
|
19
|
+
@retry_subscription = ActiveSupport::Notifications.subscribe('enqueue_retry.active_job') do |*args|
|
|
20
|
+
payload = args.last
|
|
21
|
+
job = payload[:job]
|
|
22
|
+
job.send(:capture_posthog_retry, payload[:error]) if job.is_a?(ActiveJobExtensions)
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Active Job 5.2 neither emits enqueue_retry nor passes the error to retry_job.
|
|
27
|
+
module LegacyRetryReporting
|
|
28
|
+
# @api private
|
|
29
|
+
def rescue_with_handler(exception, ...)
|
|
30
|
+
previous_exception = @posthog_retry_exception
|
|
31
|
+
@posthog_retry_exception = exception
|
|
32
|
+
super
|
|
33
|
+
ensure
|
|
34
|
+
@posthog_retry_exception = previous_exception
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# @api private
|
|
38
|
+
def retry_job(...)
|
|
39
|
+
super.tap { capture_posthog_retry(@posthog_retry_exception) }
|
|
40
|
+
end
|
|
16
41
|
end
|
|
42
|
+
private_constant :LegacyRetryReporting
|
|
17
43
|
|
|
18
44
|
module ClassMethods
|
|
19
45
|
# DSL for defining how to extract distinct_id from job arguments.
|
|
@@ -91,6 +117,11 @@ module PostHog
|
|
|
91
117
|
|
|
92
118
|
private
|
|
93
119
|
|
|
120
|
+
# Completion notifications run after around_perform has restored the parent scope.
|
|
121
|
+
def posthog_logs_context
|
|
122
|
+
@posthog_execution_context || posthog_job_context
|
|
123
|
+
end
|
|
124
|
+
|
|
94
125
|
def copy_posthog_ids(data)
|
|
95
126
|
data = {} unless data.is_a?(Hash)
|
|
96
127
|
%w[distinct_id session_id].each_with_object({}) do |key, result|
|
|
@@ -143,7 +174,34 @@ module PostHog
|
|
|
143
174
|
nil
|
|
144
175
|
end
|
|
145
176
|
|
|
146
|
-
def
|
|
177
|
+
def capture_posthog_retry(exception)
|
|
178
|
+
config = PostHog::Rails.config
|
|
179
|
+
return unless config&.auto_instrument_active_job && config.report_active_job_retries && exception
|
|
180
|
+
return unless PostHog.initialized? && PostHog.client.enabled?
|
|
181
|
+
return if excluded_posthog_retry?(exception, config)
|
|
182
|
+
|
|
183
|
+
Internal::Context.with_context(
|
|
184
|
+
@posthog_execution_context || posthog_job_context, fresh: true, enrich_current_span: false
|
|
185
|
+
) do
|
|
186
|
+
capture_job_exception(exception, retry_failure: true)
|
|
187
|
+
end
|
|
188
|
+
rescue StandardError => e
|
|
189
|
+
PostHog::Logging.logger.error("Failed to capture job retry: #{e.class}")
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def excluded_posthog_retry?(exception, config)
|
|
193
|
+
seen = {}.compare_by_identity
|
|
194
|
+
current = exception
|
|
195
|
+
while current && seen.size < PostHog::ExceptionCapture::MAX_CHAINED_EXCEPTIONS && !seen.key?(current)
|
|
196
|
+
return true unless config.should_capture_exception?(current)
|
|
197
|
+
|
|
198
|
+
seen[current] = true
|
|
199
|
+
current = current.respond_to?(:cause) ? current.cause : nil
|
|
200
|
+
end
|
|
201
|
+
false
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def capture_job_exception(exception, retry_failure: false)
|
|
147
205
|
return unless PostHog::Rails.config&.auto_instrument_active_job
|
|
148
206
|
|
|
149
207
|
# Build distinct_id from job arguments if possible
|
|
@@ -154,7 +212,7 @@ module PostHog
|
|
|
154
212
|
end
|
|
155
213
|
|
|
156
214
|
properties = {
|
|
157
|
-
'$exception_source' => 'active_job',
|
|
215
|
+
'$exception_source' => retry_failure ? 'rails.active_job' : 'active_job',
|
|
158
216
|
'$job_class' => self.class.name,
|
|
159
217
|
'$job_id' => job_id,
|
|
160
218
|
'$queue_name' => queue_name,
|
|
@@ -162,6 +220,8 @@ module PostHog
|
|
|
162
220
|
'$job_executions' => executions
|
|
163
221
|
}
|
|
164
222
|
|
|
223
|
+
properties['$exception_level'] = 'error' if retry_failure
|
|
224
|
+
|
|
165
225
|
# Add serialized job arguments (be careful with sensitive data)
|
|
166
226
|
properties['$job_arguments'] = sanitize_job_arguments(arguments) if arguments.present?
|
|
167
227
|
|
|
@@ -169,7 +229,7 @@ module PostHog
|
|
|
169
229
|
exception,
|
|
170
230
|
distinct_id,
|
|
171
231
|
properties,
|
|
172
|
-
mechanism: { 'type' => 'active_job', 'handled' =>
|
|
232
|
+
mechanism: { 'type' => retry_failure ? 'task' : 'active_job', 'handled' => retry_failure }
|
|
173
233
|
)
|
|
174
234
|
rescue StandardError => e
|
|
175
235
|
# Don't let PostHog errors break job processing
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require 'posthog/rails/
|
|
3
|
+
require 'posthog/rails/exception_context'
|
|
4
4
|
|
|
5
5
|
module PostHog
|
|
6
6
|
module Rails
|
|
@@ -8,8 +8,6 @@ module PostHog
|
|
|
8
8
|
#
|
|
9
9
|
# @api private
|
|
10
10
|
class CaptureExceptions
|
|
11
|
-
include ParameterFilter
|
|
12
|
-
|
|
13
11
|
# @param app [#call] Rack application.
|
|
14
12
|
def initialize(app)
|
|
15
13
|
@app = app
|
|
@@ -51,8 +49,9 @@ module PostHog
|
|
|
51
49
|
|
|
52
50
|
def capture_exception(exception, env)
|
|
53
51
|
request = ActionDispatch::Request.new(env)
|
|
54
|
-
|
|
55
|
-
|
|
52
|
+
context = ExceptionContext.new(request)
|
|
53
|
+
distinct_id = context.distinct_id
|
|
54
|
+
additional_properties = { '$exception_source' => 'rails' }.merge(context.properties)
|
|
56
55
|
|
|
57
56
|
PostHog.capture_exception(
|
|
58
57
|
exception,
|
|
@@ -65,99 +64,10 @@ module PostHog
|
|
|
65
64
|
PostHog::Logging.logger.error("Backtrace: #{e.backtrace&.first(5)&.join("\n")}")
|
|
66
65
|
end
|
|
67
66
|
|
|
68
|
-
def extract_distinct_id(env)
|
|
69
|
-
# Prefer authenticated Rails user context. Request/tracing context is
|
|
70
|
-
# applied later by the core capture path if this returns nil.
|
|
71
|
-
return nil unless PostHog::Rails.config&.capture_user_context
|
|
72
|
-
|
|
73
|
-
user = extract_current_user(env['action_controller.instance'])
|
|
74
|
-
user_id = extract_user_id(user) if user
|
|
75
|
-
return user_id if present?(user_id)
|
|
76
|
-
|
|
77
|
-
nil
|
|
78
|
-
end
|
|
79
|
-
|
|
80
|
-
def extract_current_user(controller)
|
|
81
|
-
resolver = PostHog::Rails.config&.current_user_resolver
|
|
82
|
-
return resolve_current_user(resolver, controller) if resolver
|
|
83
|
-
|
|
84
|
-
method_name = PostHog::Rails.config&.current_user_method || :current_user
|
|
85
|
-
return unless controller.respond_to?(method_name, true)
|
|
86
|
-
|
|
87
|
-
controller.send(method_name)
|
|
88
|
-
end
|
|
89
|
-
|
|
90
|
-
def resolve_current_user(resolver, controller)
|
|
91
|
-
call_current_user_resolver(resolver, controller)
|
|
92
|
-
rescue StandardError => e
|
|
93
|
-
PostHog::Logging.logger.warn("current_user_resolver failed: #{e.message}")
|
|
94
|
-
nil
|
|
95
|
-
end
|
|
96
|
-
|
|
97
|
-
def call_current_user_resolver(resolver, controller)
|
|
98
|
-
if resolver.arity.zero?
|
|
99
|
-
controller ? controller.instance_exec(&resolver) : resolver.call
|
|
100
|
-
elsif controller
|
|
101
|
-
resolver.call(controller)
|
|
102
|
-
end
|
|
103
|
-
end
|
|
104
|
-
|
|
105
|
-
def extract_user_id(user)
|
|
106
|
-
# Use configured method if specified
|
|
107
|
-
method_name = PostHog::Rails.config&.user_id_method
|
|
108
|
-
return user.send(method_name) if method_name && user.respond_to?(method_name)
|
|
109
|
-
|
|
110
|
-
# Try explicit PostHog method (allows users to customize without config)
|
|
111
|
-
return user.posthog_distinct_id if user.respond_to?(:posthog_distinct_id)
|
|
112
|
-
return user.distinct_id if user.respond_to?(:distinct_id)
|
|
113
|
-
|
|
114
|
-
# Try common ID methods
|
|
115
|
-
return user.id if user.respond_to?(:id)
|
|
116
|
-
return user['id'] if user.respond_to?(:[]) && user['id']
|
|
117
|
-
return user.pk if user.respond_to?(:pk)
|
|
118
|
-
return user['pk'] if user.respond_to?(:[]) && user['pk']
|
|
119
|
-
return user.uuid if user.respond_to?(:uuid)
|
|
120
|
-
return user['uuid'] if user.respond_to?(:[]) && user['uuid']
|
|
121
|
-
|
|
122
|
-
user.to_s
|
|
123
|
-
end
|
|
124
|
-
|
|
125
|
-
def build_properties(request, env)
|
|
126
|
-
properties = {
|
|
127
|
-
'$exception_source' => 'rails'
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
# Add controller and action if available
|
|
131
|
-
if env['action_controller.instance']
|
|
132
|
-
controller = env['action_controller.instance']
|
|
133
|
-
properties['$controller'] = safe_serialize(controller.controller_name)
|
|
134
|
-
properties['$action'] = safe_serialize(controller.action_name)
|
|
135
|
-
end
|
|
136
|
-
|
|
137
|
-
# Add request parameters (be careful with sensitive data)
|
|
138
|
-
if request.params.present?
|
|
139
|
-
filtered_params = filter_sensitive_params(request.params)
|
|
140
|
-
# Safe serialize to handle any complex objects in params
|
|
141
|
-
properties['$request_params'] = safe_serialize(filtered_params) unless filtered_params.empty?
|
|
142
|
-
end
|
|
143
|
-
|
|
144
|
-
response_status_code = env['posthog.response_status_code']
|
|
145
|
-
properties['$response_status_code'] = response_status_code if response_status_code
|
|
146
|
-
|
|
147
|
-
# Add referrer
|
|
148
|
-
properties['$referrer'] = safe_serialize(request.referrer) if request.referrer
|
|
149
|
-
|
|
150
|
-
properties
|
|
151
|
-
end
|
|
152
|
-
|
|
153
67
|
def response_status(response)
|
|
154
68
|
status = response.respond_to?(:[]) ? response[0] : nil
|
|
155
69
|
status if status.is_a?(Integer)
|
|
156
70
|
end
|
|
157
|
-
|
|
158
|
-
def present?(value)
|
|
159
|
-
!(value.nil? || (value.respond_to?(:empty?) && value.empty?))
|
|
160
|
-
end
|
|
161
71
|
end
|
|
162
72
|
end
|
|
163
73
|
end
|
|
@@ -19,6 +19,10 @@ module PostHog
|
|
|
19
19
|
# @return [Boolean] Whether to automatically instrument ActiveJob. Defaults to false.
|
|
20
20
|
attr_accessor :auto_instrument_active_job
|
|
21
21
|
|
|
22
|
+
# @return [Boolean] Whether to report each Active Job retry failure. Requires auto_instrument_active_job.
|
|
23
|
+
# Defaults to false.
|
|
24
|
+
attr_accessor :report_active_job_retries
|
|
25
|
+
|
|
22
26
|
# @return [Array<String>] Exception class names to ignore in addition to the defaults.
|
|
23
27
|
attr_accessor :excluded_exceptions
|
|
24
28
|
|
|
@@ -47,6 +51,11 @@ module PostHog
|
|
|
47
51
|
# (only takes effect when {#logs_enabled} is true).
|
|
48
52
|
attr_accessor :logs_forward_rails_logger
|
|
49
53
|
|
|
54
|
+
# @return [Array<Symbol>] Components whose notifications produce structured logs. Defaults to [].
|
|
55
|
+
# Supports :action_controller, :active_record, :active_job, and :action_mailer.
|
|
56
|
+
# Only takes effect when logs_enabled is true; components are not loaded automatically.
|
|
57
|
+
attr_accessor :logs_notifications
|
|
58
|
+
|
|
50
59
|
# @return [Integer, Symbol, nil] Minimum severity to forward to PostHog Logs. When nil, inherits the
|
|
51
60
|
# current Rails.logger level. Accepts a Logger severity constant (e.g. Logger::INFO) or symbol (:info).
|
|
52
61
|
attr_accessor :logs_level
|
|
@@ -68,6 +77,7 @@ module PostHog
|
|
|
68
77
|
@auto_capture_exceptions = false
|
|
69
78
|
@report_rescued_exceptions = false
|
|
70
79
|
@auto_instrument_active_job = false
|
|
80
|
+
@report_active_job_retries = false
|
|
71
81
|
@excluded_exceptions = []
|
|
72
82
|
@use_tracing_headers = true
|
|
73
83
|
@capture_user_context = true
|
|
@@ -76,6 +86,7 @@ module PostHog
|
|
|
76
86
|
@user_id_method = nil
|
|
77
87
|
@logs_enabled = false
|
|
78
88
|
@logs_forward_rails_logger = true
|
|
89
|
+
@logs_notifications = []
|
|
79
90
|
@logs_level = nil
|
|
80
91
|
@logs_max_records_per_minute = DEFAULT_LOGS_MAX_RECORDS_PER_MINUTE
|
|
81
92
|
@logs_before_send = nil
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'posthog/rails/exception_context'
|
|
4
|
+
|
|
5
|
+
module PostHog
|
|
6
|
+
module Rails
|
|
7
|
+
module ControllerHelpers
|
|
8
|
+
private
|
|
9
|
+
|
|
10
|
+
# Report a handled exception with filtered Rails request context.
|
|
11
|
+
# Manual reporting is independent of automatic capture and its exclusions.
|
|
12
|
+
#
|
|
13
|
+
# @param exception [Exception, String, Object] Input accepted by {PostHog::Client#capture_exception}.
|
|
14
|
+
# @param distinct_id [String, nil] Explicit identity, before configured user and request identity.
|
|
15
|
+
# @param additional_properties [Hash, nil] Explicit properties override inferred request properties.
|
|
16
|
+
# @param flags [PostHog::FeatureFlagEvaluations, nil] Flag evaluation snapshot.
|
|
17
|
+
# @param mechanism [Hash, nil] Explicit exception mechanism; defaults to core manual capture semantics.
|
|
18
|
+
# @return [Boolean, nil] The result of {PostHog.capture_exception}, or false when unavailable or capture fails.
|
|
19
|
+
def capture_exception(exception, distinct_id = nil, additional_properties = {}, flags: nil, mechanism: nil)
|
|
20
|
+
return false unless PostHog.initialized? && PostHog.client.enabled?
|
|
21
|
+
|
|
22
|
+
context = ExceptionContext.new(request, self, manual: true)
|
|
23
|
+
distinct_id = context.distinct_id if distinct_id.nil?
|
|
24
|
+
properties = context.properties.merge(additional_properties || {})
|
|
25
|
+
|
|
26
|
+
PostHog.capture_exception(exception, distinct_id, properties, flags: flags, mechanism: mechanism)
|
|
27
|
+
rescue StandardError
|
|
28
|
+
PostHog::Logging.logger.error('Failed to capture controller exception')
|
|
29
|
+
false
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
@@ -19,7 +19,9 @@ module PostHog
|
|
|
19
19
|
# @return [void]
|
|
20
20
|
def report(error, handled:, severity:, context:, source: nil)
|
|
21
21
|
return unless PostHog::Rails.config&.auto_capture_exceptions
|
|
22
|
-
|
|
22
|
+
|
|
23
|
+
runner_report = !handled && source == 'application.runner.railties'
|
|
24
|
+
return unless runner_report || PostHog::Rails.config&.should_capture_exception?(error)
|
|
23
25
|
|
|
24
26
|
if defined?(::Sidekiq::JobRetry::Handled) && error.is_a?(::Sidekiq::JobRetry::Handled)
|
|
25
27
|
error = error.cause || error
|
|
@@ -43,6 +45,12 @@ module PostHog
|
|
|
43
45
|
end
|
|
44
46
|
end
|
|
45
47
|
|
|
48
|
+
# Keep the reporter's object and serialized context until terminal capture.
|
|
49
|
+
if runner_report
|
|
50
|
+
Thread.current[:posthog_rails_runner_report] = [error, distinct_id, properties]
|
|
51
|
+
return
|
|
52
|
+
end
|
|
53
|
+
|
|
46
54
|
PostHog.capture_exception(
|
|
47
55
|
error,
|
|
48
56
|
distinct_id,
|
|
@@ -53,6 +61,27 @@ module PostHog
|
|
|
53
61
|
PostHog::Logging.logger.error("Failed to report error via subscriber: #{e.message}")
|
|
54
62
|
PostHog::Logging.logger.error("Backtrace: #{e.backtrace&.first(5)&.join("\n")}")
|
|
55
63
|
end
|
|
64
|
+
|
|
65
|
+
def self.take_runner_report(exception)
|
|
66
|
+
report = Thread.current[:posthog_rails_runner_report]
|
|
67
|
+
Thread.current[:posthog_rails_runner_report] = nil
|
|
68
|
+
return report if report && report.first.equal?(exception)
|
|
69
|
+
|
|
70
|
+
# Rails also converts inline errors when --skip-executor prevents a report.
|
|
71
|
+
# Only its command conversion may replace the terminal exception.
|
|
72
|
+
return unless exception.is_a?(SystemExit) && exception.status == 1
|
|
73
|
+
|
|
74
|
+
original = exception.cause
|
|
75
|
+
return unless original.is_a?(NameError) || original.is_a?(SyntaxError)
|
|
76
|
+
return unless defined?(::Rails::Command::RunnerCommand)
|
|
77
|
+
|
|
78
|
+
# Inline eval shares Rails' filename, so also check the caller beyond exit.
|
|
79
|
+
location = exception.backtrace_locations&.find { |frame| frame.base_label != 'exit' }
|
|
80
|
+
return unless location&.base_label == 'perform'
|
|
81
|
+
return unless location.path == ::Rails::Command::RunnerCommand.instance_method(:perform).source_location.first
|
|
82
|
+
|
|
83
|
+
report && report.first.equal?(original) ? report : [original, nil, {}]
|
|
84
|
+
end
|
|
56
85
|
end
|
|
57
86
|
end
|
|
58
87
|
end
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'posthog/rails/parameter_filter'
|
|
4
|
+
require 'posthog/rails/request_metadata'
|
|
5
|
+
|
|
6
|
+
module PostHog
|
|
7
|
+
module Rails
|
|
8
|
+
# Shared request enrichment for automatic and manual exception capture.
|
|
9
|
+
#
|
|
10
|
+
# @api private
|
|
11
|
+
class ExceptionContext
|
|
12
|
+
include ParameterFilter
|
|
13
|
+
|
|
14
|
+
def initialize(request, controller = request.env['action_controller.instance'], manual: false)
|
|
15
|
+
@request = request
|
|
16
|
+
@controller = controller
|
|
17
|
+
@manual = manual
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
def distinct_id
|
|
21
|
+
# Prefer authenticated Rails user context. Request/tracing context is
|
|
22
|
+
# applied later by the core capture path if this returns nil.
|
|
23
|
+
return nil unless PostHog::Rails.config&.capture_user_context
|
|
24
|
+
|
|
25
|
+
user = extract_current_user(@controller)
|
|
26
|
+
user_id = extract_user_id(user) if user
|
|
27
|
+
return user_id if present?(user_id)
|
|
28
|
+
|
|
29
|
+
nil
|
|
30
|
+
rescue StandardError
|
|
31
|
+
raise unless @manual
|
|
32
|
+
|
|
33
|
+
nil
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def properties
|
|
37
|
+
request = @request
|
|
38
|
+
env = request.env
|
|
39
|
+
properties = @manual ? RequestMetadata.extract(request) : {}
|
|
40
|
+
|
|
41
|
+
# Add controller and action if available
|
|
42
|
+
if @controller
|
|
43
|
+
controller = @controller
|
|
44
|
+
properties['$controller'] = safe_serialize(controller.controller_name)
|
|
45
|
+
properties['$action'] = safe_serialize(controller.action_name)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# Add request parameters (be careful with sensitive data)
|
|
49
|
+
params = request_parameters
|
|
50
|
+
if params.present?
|
|
51
|
+
filtered_params = filter_request_parameters(params)
|
|
52
|
+
# Safe serialize to handle any complex objects in params
|
|
53
|
+
properties['$request_params'] = safe_serialize(filtered_params) unless filtered_params.empty?
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
status = env['posthog.response_status_code']
|
|
57
|
+
status ||= @controller.response.status if @manual && @controller&.performed?
|
|
58
|
+
properties['$response_status_code'] = status if status
|
|
59
|
+
|
|
60
|
+
# Add referrer
|
|
61
|
+
properties['$referrer'] = safe_serialize(request.referrer) if request.referrer
|
|
62
|
+
|
|
63
|
+
if @manual
|
|
64
|
+
%w[$current_url $referrer].each do |key|
|
|
65
|
+
properties[key] = properties[key].split(/[?#]/, 2).first if properties[key]
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
properties
|
|
70
|
+
rescue StandardError
|
|
71
|
+
raise unless @manual
|
|
72
|
+
|
|
73
|
+
{}
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
def request_parameters
|
|
79
|
+
return @request.params unless @manual
|
|
80
|
+
|
|
81
|
+
# Only Rails-owned parsed caches are safe to read without invoking body-parser diagnostics.
|
|
82
|
+
cached = @request.get_header('action_dispatch.request.parameters')
|
|
83
|
+
return cached if cached.is_a?(Hash)
|
|
84
|
+
|
|
85
|
+
body = @request.get_header('action_dispatch.request.request_parameters')
|
|
86
|
+
body = {} unless body.is_a?(Hash)
|
|
87
|
+
body.merge(@request.query_parameters).merge(@request.path_parameters)
|
|
88
|
+
rescue StandardError
|
|
89
|
+
raise unless @manual
|
|
90
|
+
|
|
91
|
+
{}
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def filter_request_parameters(params)
|
|
95
|
+
if @manual && @request.has_header?('action_dispatch.parameter_filter')
|
|
96
|
+
ParameterFilter.backend.new(@request.get_header('action_dispatch.parameter_filter')).filter(params)
|
|
97
|
+
else
|
|
98
|
+
filter_sensitive_params(params)
|
|
99
|
+
end
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def extract_current_user(controller)
|
|
103
|
+
resolver = PostHog::Rails.config&.current_user_resolver
|
|
104
|
+
return resolve_current_user(resolver, controller) if resolver
|
|
105
|
+
|
|
106
|
+
method_name = PostHog::Rails.config&.current_user_method || :current_user
|
|
107
|
+
return unless controller.respond_to?(method_name, true)
|
|
108
|
+
|
|
109
|
+
controller.send(method_name)
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def resolve_current_user(resolver, controller)
|
|
113
|
+
call_current_user_resolver(resolver, controller)
|
|
114
|
+
rescue StandardError => e
|
|
115
|
+
message = @manual ? 'current_user_resolver failed' : "current_user_resolver failed: #{e.message}"
|
|
116
|
+
PostHog::Logging.logger.warn(message)
|
|
117
|
+
nil
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def call_current_user_resolver(resolver, controller)
|
|
121
|
+
if resolver.arity.zero?
|
|
122
|
+
controller ? controller.instance_exec(&resolver) : resolver.call
|
|
123
|
+
elsif controller
|
|
124
|
+
resolver.call(controller)
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def extract_user_id(user)
|
|
129
|
+
# Use configured method if specified
|
|
130
|
+
method_name = PostHog::Rails.config&.user_id_method
|
|
131
|
+
return user.send(method_name) if method_name && user.respond_to?(method_name)
|
|
132
|
+
|
|
133
|
+
# Try explicit PostHog method (allows users to customize without config)
|
|
134
|
+
return user.posthog_distinct_id if user.respond_to?(:posthog_distinct_id)
|
|
135
|
+
return user.distinct_id if user.respond_to?(:distinct_id)
|
|
136
|
+
|
|
137
|
+
# Try common ID methods
|
|
138
|
+
return user.id if user.respond_to?(:id)
|
|
139
|
+
return user['id'] if user.respond_to?(:[]) && user['id']
|
|
140
|
+
return user.pk if user.respond_to?(:pk)
|
|
141
|
+
return user['pk'] if user.respond_to?(:[]) && user['pk']
|
|
142
|
+
return user.uuid if user.respond_to?(:uuid)
|
|
143
|
+
return user['uuid'] if user.respond_to?(:[]) && user['uuid']
|
|
144
|
+
|
|
145
|
+
user.to_s
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def present?(value)
|
|
149
|
+
!(value.nil? || (value.respond_to?(:empty?) && value.empty?))
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
private_constant :ExceptionContext
|
|
154
|
+
end
|
|
155
|
+
end
|
|
@@ -74,18 +74,22 @@ module PostHog
|
|
|
74
74
|
# which, as an Exception, escapes the rescue below and breaks the app.
|
|
75
75
|
REENTRANCY_KEY = :posthog_rails_logs_emitting
|
|
76
76
|
|
|
77
|
+
def accepts_severity?(severity)
|
|
78
|
+
severity >= @threshold
|
|
79
|
+
end
|
|
80
|
+
|
|
77
81
|
# Mirrors `Logger#add` message/progname resolution, then emits to OTel
|
|
78
82
|
# instead of writing to a log device.
|
|
79
83
|
#
|
|
80
84
|
# @return [Boolean] Always true so it composes with broadcast loggers.
|
|
81
|
-
def add(severity, message = nil, progname = nil)
|
|
85
|
+
def add(severity, message = nil, progname = nil, attributes: {})
|
|
82
86
|
return true if Thread.current[REENTRANCY_KEY]
|
|
83
87
|
|
|
84
88
|
begin
|
|
85
89
|
Thread.current[REENTRANCY_KEY] = true
|
|
86
90
|
|
|
87
91
|
severity ||= ::Logger::UNKNOWN
|
|
88
|
-
return true
|
|
92
|
+
return true unless accepts_severity?(severity)
|
|
89
93
|
|
|
90
94
|
if message.nil?
|
|
91
95
|
if block_given?
|
|
@@ -99,7 +103,9 @@ module PostHog
|
|
|
99
103
|
return true if message.nil?
|
|
100
104
|
return true if self_log?(message, progname)
|
|
101
105
|
|
|
102
|
-
record =
|
|
106
|
+
record = build_record(severity, message, progname)
|
|
107
|
+
record[:attributes].merge!(attributes)
|
|
108
|
+
record = apply_before_send(record)
|
|
103
109
|
return true if record.nil?
|
|
104
110
|
|
|
105
111
|
case @rate_limiter&.record
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'active_support/lazy_load_hooks'
|
|
5
|
+
require 'active_support/notifications'
|
|
6
|
+
require 'posthog/rails/parameter_filter'
|
|
7
|
+
require 'posthog/internal/context'
|
|
8
|
+
|
|
9
|
+
module PostHog
|
|
10
|
+
module Rails
|
|
11
|
+
module Logs
|
|
12
|
+
# Optional completion records, sharing the ordinary logger's sink and controls.
|
|
13
|
+
# @api private
|
|
14
|
+
module Notifications
|
|
15
|
+
class UnsafeParameters < StandardError; end
|
|
16
|
+
private_constant :UnsafeParameters
|
|
17
|
+
|
|
18
|
+
EVENTS = {
|
|
19
|
+
action_controller: %w[process_action.action_controller],
|
|
20
|
+
active_record: %w[sql.active_record],
|
|
21
|
+
active_job: %w[enqueue.active_job enqueue_at.active_job perform.active_job
|
|
22
|
+
enqueue_retry.active_job retry_stopped.active_job discard.active_job],
|
|
23
|
+
action_mailer: %w[process.action_mailer deliver.action_mailer]
|
|
24
|
+
}.freeze
|
|
25
|
+
SQL_OPERATION = /\A\s*(
|
|
26
|
+
SELECT|INSERT|UPDATE|DELETE|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|WITH|CREATE|ALTER|DROP|PRAGMA|EXPLAIN
|
|
27
|
+
)\b/ix
|
|
28
|
+
BODIES = {
|
|
29
|
+
action_controller: 'Rails controller request completed',
|
|
30
|
+
active_record: 'Rails SQL query completed',
|
|
31
|
+
active_job: 'Rails job lifecycle event',
|
|
32
|
+
action_mailer: 'Rails mailer lifecycle event'
|
|
33
|
+
}.freeze
|
|
34
|
+
|
|
35
|
+
class << self
|
|
36
|
+
def install(appender)
|
|
37
|
+
@appender = appender
|
|
38
|
+
selections = PostHog::Rails.config.logs_notifications
|
|
39
|
+
@components = selections.is_a?(Array) ? selections & EVENTS.keys : []
|
|
40
|
+
if !selections.is_a?(Array) || (selections - EVENTS.keys).any?
|
|
41
|
+
PostHog::Logging.logger.warn('Invalid logs_notifications selection; ignoring unknown components')
|
|
42
|
+
end
|
|
43
|
+
@hooked ||= {}
|
|
44
|
+
@loaded ||= {}
|
|
45
|
+
@subscriptions ||= {}
|
|
46
|
+
@components.each do |component|
|
|
47
|
+
unless @hooked[component]
|
|
48
|
+
@hooked[component] = true
|
|
49
|
+
ActiveSupport.on_load(component) { Notifications.component_loaded(component) }
|
|
50
|
+
end
|
|
51
|
+
subscribe(component) if @loaded[component]
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def component_loaded(component)
|
|
56
|
+
@loaded[component] = true
|
|
57
|
+
subscribe(component) if @appender && @components.include?(component)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def reset
|
|
61
|
+
(@subscriptions || {}).each_value do |subscriptions|
|
|
62
|
+
subscriptions.each { |subscription| ActiveSupport::Notifications.unsubscribe(subscription) }
|
|
63
|
+
end
|
|
64
|
+
@subscriptions = {}
|
|
65
|
+
@components = []
|
|
66
|
+
@appender = nil
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
private
|
|
70
|
+
|
|
71
|
+
def subscribe(component)
|
|
72
|
+
return if @subscriptions.key?(component)
|
|
73
|
+
|
|
74
|
+
@subscriptions[component] = EVENTS.fetch(component).map do |name|
|
|
75
|
+
ActiveSupport::Notifications.subscribe(name) do |*args|
|
|
76
|
+
capture(component, ActiveSupport::Notifications::Event.new(*args))
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def capture(component, event)
|
|
82
|
+
return unless @appender && PostHog::Rails.config.logs_enabled
|
|
83
|
+
return unless PostHog.initialized? && PostHog.client.enabled?
|
|
84
|
+
return if Thread.current[Appender::REENTRANCY_KEY]
|
|
85
|
+
|
|
86
|
+
payload = event.payload
|
|
87
|
+
error = payload[:exception_object] || payload[:error]
|
|
88
|
+
if component == :active_job && %w[enqueue.active_job enqueue_at.active_job].include?(event.name) &&
|
|
89
|
+
payload[:job].respond_to?(:enqueue_error)
|
|
90
|
+
error ||= payload[:job].enqueue_error
|
|
91
|
+
end
|
|
92
|
+
error_type = error ? error.class.name : Array(payload[:exception]).first
|
|
93
|
+
severity = severity_for(component, payload, error_type)
|
|
94
|
+
return unless @appender.accepts_severity?(severity)
|
|
95
|
+
|
|
96
|
+
attributes = build_attributes(component, event)
|
|
97
|
+
attributes['error.type'] = error_type if error_type.is_a?(String)
|
|
98
|
+
emit_in_context(component, payload) do
|
|
99
|
+
@appender.add(severity, BODIES.fetch(component), attributes: attributes)
|
|
100
|
+
end
|
|
101
|
+
rescue StandardError => e
|
|
102
|
+
return if @warned
|
|
103
|
+
|
|
104
|
+
@warned = true
|
|
105
|
+
PostHog::Logging.logger.warn("PostHog notification log failed (#{e.class}); dropping the record")
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Parameter filters are application callbacks and can themselves log or query.
|
|
109
|
+
def build_attributes(component, event)
|
|
110
|
+
Thread.current[Appender::REENTRANCY_KEY] = true
|
|
111
|
+
{ 'event.name' => event.name }.merge(attributes_for(component, event.payload))
|
|
112
|
+
ensure
|
|
113
|
+
Thread.current[Appender::REENTRANCY_KEY] = nil
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def emit_in_context(component, payload, &block)
|
|
117
|
+
job = payload[:job]
|
|
118
|
+
if component == :active_job && PostHog::Rails.config.auto_instrument_active_job &&
|
|
119
|
+
job.respond_to?(:posthog_logs_context, true)
|
|
120
|
+
Internal::Context.with_context(
|
|
121
|
+
job.send(:posthog_logs_context), fresh: true, owner: PostHog.client, enrich_current_span: false, &block
|
|
122
|
+
)
|
|
123
|
+
else
|
|
124
|
+
yield
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def attributes_for(component, payload)
|
|
129
|
+
case component
|
|
130
|
+
when :action_controller
|
|
131
|
+
attributes = pick(payload, controller: 'rails.controller', action: 'rails.action',
|
|
132
|
+
method: 'http.request.method', status: 'http.response.status_code')
|
|
133
|
+
if payload[:params].is_a?(Hash)
|
|
134
|
+
attributes['rails.params'] =
|
|
135
|
+
bounded_json(controller_params(payload[:params]))
|
|
136
|
+
end
|
|
137
|
+
attributes
|
|
138
|
+
when :active_record
|
|
139
|
+
attributes = pick(payload, name: 'rails.sql.name', cached: 'rails.sql.cached')
|
|
140
|
+
# Never export statements: even SQL without binds may contain literal secrets.
|
|
141
|
+
operation = payload[:sql].to_s[SQL_OPERATION, 1]
|
|
142
|
+
attributes['db.operation.name'] = operation.upcase if operation
|
|
143
|
+
attributes
|
|
144
|
+
when :active_job
|
|
145
|
+
job_attributes(payload)
|
|
146
|
+
when :action_mailer
|
|
147
|
+
pick(payload, mailer: 'rails.mailer', action: 'rails.action')
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def job_attributes(payload)
|
|
152
|
+
job = payload[:job]
|
|
153
|
+
return {} unless job
|
|
154
|
+
|
|
155
|
+
wait = payload[:wait]
|
|
156
|
+
wait = wait.to_f if wait.is_a?(ActiveSupport::Duration)
|
|
157
|
+
attributes = pick(
|
|
158
|
+
{ job_class: job.class.name, id: job.job_id, queue: job.queue_name,
|
|
159
|
+
executions: job.executions, priority: job.priority, wait: wait },
|
|
160
|
+
job_class: 'rails.job.class', id: 'rails.job.id', queue: 'rails.job.queue',
|
|
161
|
+
executions: 'rails.job.executions', priority: 'rails.job.priority', wait: 'rails.job.retry_wait'
|
|
162
|
+
)
|
|
163
|
+
return attributes if job.class.respond_to?(:log_arguments?) && !job.class.log_arguments?
|
|
164
|
+
return attributes if defined?(::ActionMailer::MailDeliveryJob) && job.is_a?(::ActionMailer::MailDeliveryJob)
|
|
165
|
+
return attributes if defined?(::ActionMailer::DeliveryJob) && job.is_a?(::ActionMailer::DeliveryJob)
|
|
166
|
+
|
|
167
|
+
# Unkeyed arguments have no filterable name. Do not guess which are safe.
|
|
168
|
+
budget = [1000, 10_000]
|
|
169
|
+
arguments = job.arguments
|
|
170
|
+
arguments = if arguments.size > 100
|
|
171
|
+
'[FILTERED]'
|
|
172
|
+
else
|
|
173
|
+
arguments.map do |argument|
|
|
174
|
+
argument.is_a?(Hash) ? filtered_params(argument, budget) : '[FILTERED]'
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
attributes['rails.job.arguments'] = bounded_json(arguments)
|
|
178
|
+
attributes
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def pick(payload, mapping)
|
|
182
|
+
mapping.each_with_object({}) do |(key, name), attributes|
|
|
183
|
+
value = payload[key]
|
|
184
|
+
attributes[name] = safe_value(value) unless value.nil?
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# Rails controller notifications already contain request.filtered_parameters.
|
|
189
|
+
def controller_params(params)
|
|
190
|
+
copy_filter_value(params, 0, [1000, 10_000])
|
|
191
|
+
rescue UnsafeParameters
|
|
192
|
+
'[FILTERED]'
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def filtered_params(params, budget = [1000, 10_000])
|
|
196
|
+
return {} unless ::Rails.application
|
|
197
|
+
|
|
198
|
+
filters = ::Rails.application.config.filter_parameters
|
|
199
|
+
return '[FILTERED]' if filters.empty?
|
|
200
|
+
|
|
201
|
+
if ::Rails.version.to_f >= 6.0
|
|
202
|
+
require 'active_support/parameter_filter'
|
|
203
|
+
else
|
|
204
|
+
require 'action_dispatch/http/parameter_filter'
|
|
205
|
+
end
|
|
206
|
+
# Rails Proc filters can depend on key/value types and the complete original root.
|
|
207
|
+
# Never pass a normalized or partially truncated parameter tree to those callbacks.
|
|
208
|
+
filtered = ParameterFilter.backend.new(filters).filter(copy_filter_value(params, 0, budget))
|
|
209
|
+
copy_filter_value(filtered, 0, [1000, 10_000])
|
|
210
|
+
rescue UnsafeParameters
|
|
211
|
+
'[FILTERED]'
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
def copy_filter_value(value, depth, budget, copies = {}.compare_by_identity)
|
|
215
|
+
raise UnsafeParameters if depth > 10 || budget[0] <= 0
|
|
216
|
+
|
|
217
|
+
budget[0] -= 1
|
|
218
|
+
case value
|
|
219
|
+
when String, Symbol
|
|
220
|
+
budget[1] -= value.bytesize if value.is_a?(String)
|
|
221
|
+
budget[1] -= value.to_s.bytesize if value.is_a?(Symbol)
|
|
222
|
+
raise UnsafeParameters if budget[1].negative?
|
|
223
|
+
|
|
224
|
+
copies[value] ||= value.clone
|
|
225
|
+
when Integer, Float, true, false, nil
|
|
226
|
+
value
|
|
227
|
+
when Array, Hash
|
|
228
|
+
raise UnsafeParameters if value.size > 100
|
|
229
|
+
|
|
230
|
+
copy = value.clone(freeze: false).clear
|
|
231
|
+
if value.is_a?(Hash)
|
|
232
|
+
raise UnsafeParameters if value.default_proc
|
|
233
|
+
|
|
234
|
+
copy.default = copy_filter_value(value.default, depth + 1, budget, copies) unless value.default.nil?
|
|
235
|
+
value.each do |key, item|
|
|
236
|
+
raise UnsafeParameters unless key.is_a?(String) || key.is_a?(Symbol)
|
|
237
|
+
|
|
238
|
+
copied_key = copy_filter_value(key, depth + 1, budget, copies)
|
|
239
|
+
copy[copied_key] = copy_filter_value(item, depth + 1, budget, copies)
|
|
240
|
+
end
|
|
241
|
+
else
|
|
242
|
+
value.each { |item| copy << copy_filter_value(item, depth + 1, budget, copies) }
|
|
243
|
+
end
|
|
244
|
+
copy.freeze if value.frozen?
|
|
245
|
+
copies[value] ||= copy
|
|
246
|
+
else
|
|
247
|
+
raise UnsafeParameters
|
|
248
|
+
end
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
def bounded_json(value)
|
|
252
|
+
json = JSON.generate(value)
|
|
253
|
+
json.bytesize <= 10_000 ? json : JSON.generate('[FILTERED: payload too large]')
|
|
254
|
+
rescue JSON::GeneratorError
|
|
255
|
+
JSON.generate('[FILTERED]')
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# Bound traversal and omit arbitrary object inspection from notification payloads.
|
|
259
|
+
def safe_value(value, depth = 0, budget = [1000])
|
|
260
|
+
return '[FILTERED]' if depth > 10 || budget[0] <= 0
|
|
261
|
+
|
|
262
|
+
budget[0] -= 1
|
|
263
|
+
|
|
264
|
+
case value
|
|
265
|
+
when String then value[0, 10_000].dup
|
|
266
|
+
when Symbol then value.to_s
|
|
267
|
+
when Integer, Float, true, false, nil then value
|
|
268
|
+
when Array then value.first(100).map { |item| safe_value(item, depth + 1, budget) }
|
|
269
|
+
when Hash
|
|
270
|
+
value.first(100).each_with_object({}) do |(key, item), result|
|
|
271
|
+
next unless key.is_a?(String) || key.is_a?(Symbol)
|
|
272
|
+
|
|
273
|
+
result[key.to_s] = safe_value(item, depth + 1, budget)
|
|
274
|
+
end
|
|
275
|
+
else '[FILTERED]'
|
|
276
|
+
end
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
def severity_for(component, payload, error_type)
|
|
280
|
+
return ::Logger::ERROR if error_type
|
|
281
|
+
return ::Logger::DEBUG if component == :active_record
|
|
282
|
+
|
|
283
|
+
status = payload[:status]
|
|
284
|
+
return ::Logger::ERROR if status.is_a?(Integer) && status >= 500
|
|
285
|
+
return ::Logger::WARN if status.is_a?(Integer) && status >= 400
|
|
286
|
+
|
|
287
|
+
::Logger::INFO
|
|
288
|
+
end
|
|
289
|
+
end
|
|
290
|
+
end
|
|
291
|
+
end
|
|
292
|
+
end
|
|
293
|
+
end
|
|
@@ -5,6 +5,7 @@ require 'posthog/logging'
|
|
|
5
5
|
require 'posthog/rails/configuration'
|
|
6
6
|
require 'posthog/rails/logs/appender'
|
|
7
7
|
require 'posthog/rails/logs/rate_limiter'
|
|
8
|
+
require 'posthog/rails/logs/notifications'
|
|
8
9
|
|
|
9
10
|
module PostHog
|
|
10
11
|
module Rails
|
|
@@ -68,6 +69,8 @@ module PostHog
|
|
|
68
69
|
rate_limiter: build_rate_limiter(config),
|
|
69
70
|
before_send: config.logs_before_send
|
|
70
71
|
)
|
|
72
|
+
Notifications.install(@appender) if config.logs_enabled
|
|
73
|
+
@appender
|
|
71
74
|
rescue StandardError => e
|
|
72
75
|
warn_once("Failed to initialize PostHog Logs: #{e.message}")
|
|
73
76
|
nil
|
|
@@ -78,6 +81,7 @@ module PostHog
|
|
|
78
81
|
# @param timeout [Numeric] Max seconds to spend; see {SHUTDOWN_TIMEOUT_SECONDS}.
|
|
79
82
|
# @return [void]
|
|
80
83
|
def shutdown(timeout: SHUTDOWN_TIMEOUT_SECONDS)
|
|
84
|
+
Notifications.reset
|
|
81
85
|
@provider&.shutdown(timeout: timeout)
|
|
82
86
|
rescue StandardError => e
|
|
83
87
|
logger.warn("Error shutting down PostHog Logs: #{e.message}")
|
|
@@ -102,6 +106,7 @@ module PostHog
|
|
|
102
106
|
#
|
|
103
107
|
# @return [void]
|
|
104
108
|
def reset
|
|
109
|
+
Notifications.reset
|
|
105
110
|
@installed = false
|
|
106
111
|
@provider = nil
|
|
107
112
|
@appender = nil
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require 'English'
|
|
3
4
|
require 'posthog/rails/facade'
|
|
4
5
|
|
|
5
6
|
module PostHog
|
|
@@ -11,6 +12,13 @@ module PostHog
|
|
|
11
12
|
PostHog::Rails.install_posthog_facade!
|
|
12
13
|
end
|
|
13
14
|
|
|
15
|
+
initializer 'posthog.controller_helpers' do
|
|
16
|
+
ActiveSupport.on_load(:action_controller) do
|
|
17
|
+
include PostHog::Rails::ControllerHelpers unless method_defined?(:capture_exception) ||
|
|
18
|
+
private_method_defined?(:capture_exception)
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
14
22
|
# Insert middleware for request context and exception capturing
|
|
15
23
|
initializer 'posthog.insert_middlewares' do |app|
|
|
16
24
|
# Wrap the Rails exception middleware so request context is active for
|
|
@@ -81,17 +89,45 @@ module PostHog
|
|
|
81
89
|
install_posthog_logs if PostHog::Rails.config&.logs_enabled
|
|
82
90
|
end
|
|
83
91
|
|
|
92
|
+
runner_started = false
|
|
93
|
+
runner { runner_started = true }
|
|
94
|
+
|
|
84
95
|
# Ensure PostHog shuts down gracefully (register only once)
|
|
85
96
|
config.after_initialize do
|
|
86
97
|
next if @posthog_at_exit_registered
|
|
87
98
|
|
|
88
99
|
@posthog_at_exit_registered = true
|
|
89
100
|
at_exit do
|
|
101
|
+
capture_runner_exception($ERROR_INFO) if runner_started
|
|
90
102
|
PostHog::Rails::Logs::Setup.shutdown
|
|
91
103
|
PostHog.client&.shutdown if PostHog.initialized?
|
|
92
104
|
end
|
|
93
105
|
end
|
|
94
106
|
|
|
107
|
+
# Use the same exit hook so the terminating event is queued before shutdown
|
|
108
|
+
# drains the client, including on Rails versions without runner error reports.
|
|
109
|
+
def self.capture_runner_exception(exception)
|
|
110
|
+
report = ErrorSubscriber.take_runner_report(exception)
|
|
111
|
+
return unless exception
|
|
112
|
+
return if exception.is_a?(SystemExit) && exception.success?
|
|
113
|
+
return if exception.is_a?(SignalException)
|
|
114
|
+
|
|
115
|
+
exception, distinct_id, properties = report if report
|
|
116
|
+
return unless PostHog.initialized? && PostHog.client.enabled?
|
|
117
|
+
return unless PostHog::Rails.config&.auto_capture_exceptions
|
|
118
|
+
return unless PostHog::Rails.config.should_capture_exception?(exception)
|
|
119
|
+
|
|
120
|
+
PostHog.capture_exception(
|
|
121
|
+
exception,
|
|
122
|
+
distinct_id,
|
|
123
|
+
(properties || {}).merge('$exception_source' => 'rails.runner', '$exception_level' => 'fatal'),
|
|
124
|
+
mechanism: { 'type' => 'at_exit', 'handled' => false, 'synthetic' => false }
|
|
125
|
+
)
|
|
126
|
+
rescue Exception => e # rubocop:disable Lint/RescueException -- Reporting must not replace the terminating exception.
|
|
127
|
+
PostHog::Logging.logger.warn("Failed to capture Rails runner exception: #{e.class}: #{e.message}")
|
|
128
|
+
end
|
|
129
|
+
private_class_method :capture_runner_exception
|
|
130
|
+
|
|
95
131
|
MISSING_MIDDLEWARE_MESSAGE = 'No such middleware to insert'
|
|
96
132
|
MIDDLEWARE_FALLBACK_OPERATION = :posthog_insert_middleware_with_fallback
|
|
97
133
|
|
|
@@ -79,12 +79,13 @@ module PostHog
|
|
|
79
79
|
private
|
|
80
80
|
|
|
81
81
|
def capture_streaming_exception(exception, source, env = nil)
|
|
82
|
-
|
|
82
|
+
context = ExceptionContext.new(ActionDispatch::Request.new(env)) if env
|
|
83
|
+
properties = context ? context.properties : {}
|
|
83
84
|
properties['$exception_source'] = source
|
|
84
85
|
properties['$exception_level'] = 'error'
|
|
85
86
|
PostHog.capture_exception(
|
|
86
87
|
exception,
|
|
87
|
-
|
|
88
|
+
context&.distinct_id,
|
|
88
89
|
properties,
|
|
89
90
|
mechanism: { 'type' => 'middleware', 'handled' => false }
|
|
90
91
|
)
|
data/lib/posthog/rails.rb
CHANGED
|
@@ -6,6 +6,7 @@ require 'posthog/rails/tracing_headers'
|
|
|
6
6
|
require 'posthog/rails/request_metadata'
|
|
7
7
|
require 'posthog/rails/request_context'
|
|
8
8
|
require 'posthog/rails/capture_exceptions'
|
|
9
|
+
require 'posthog/rails/controller_helpers'
|
|
9
10
|
require 'posthog/rails/streaming_exceptions'
|
|
10
11
|
require 'posthog/rails/rescued_exception_interceptor'
|
|
11
12
|
require 'posthog/rails/active_job'
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: posthog-rails
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 3.
|
|
4
|
+
version: 3.24.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- PostHog
|
|
@@ -52,9 +52,12 @@ files:
|
|
|
52
52
|
- lib/posthog/rails/active_job.rb
|
|
53
53
|
- lib/posthog/rails/capture_exceptions.rb
|
|
54
54
|
- lib/posthog/rails/configuration.rb
|
|
55
|
+
- lib/posthog/rails/controller_helpers.rb
|
|
55
56
|
- lib/posthog/rails/error_subscriber.rb
|
|
57
|
+
- lib/posthog/rails/exception_context.rb
|
|
56
58
|
- lib/posthog/rails/facade.rb
|
|
57
59
|
- lib/posthog/rails/logs/appender.rb
|
|
60
|
+
- lib/posthog/rails/logs/notifications.rb
|
|
58
61
|
- lib/posthog/rails/logs/rate_limiter.rb
|
|
59
62
|
- lib/posthog/rails/logs/setup.rb
|
|
60
63
|
- lib/posthog/rails/logs/severity.rb
|