posthog-rails 3.22.0 → 3.23.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1cb18a06ebc035ab3aadc995985ce0dffca4423d7a3f4354f35505d1728e9838
4
- data.tar.gz: f2f7532ff5015d52fe4df57bf3d4a18ce1ae823d0373ce92b514774735cf5e53
3
+ metadata.gz: eb2bfa860e2d1ca788adc0bec17f3be4a81adc3a8f0fb372589dd0e4e7bbaf05
4
+ data.tar.gz: 162adfdd32fe7a1f5ae1df7105a3bff5a6bb30163b4f63baffaa216679bb39c9
5
5
  SHA512:
6
- metadata.gz: 62379efc38117719a96bb99071337f8d4809fcf46786268cfa578a51894f4ef0d3d1bb048f4c20b11d15062c83cca8af1ca2d8e14f97d570b0cdd1aa5309469f
7
- data.tar.gz: 6d6236612649dbb5f29f47be866ef39779f5c9430b11bca847a5f69999dc76baeffc5fa30e3fbac034c3e92fbce6820464dbef4e89be2d8cb3a57547f1c62ddb
6
+ metadata.gz: 5e8cbf5fff7bbf47b38f2d8aa8f1f9bc79ac96bcd45853b11ecd950a94b0cb9ca8ff921f15b143a63b04ff6ace705a3d7464856b68653e50d96cd9394b7c08ba
7
+ data.tar.gz: 1d14eadae606d7bda8cbee71891f11f65af3fa9c9af48ad9e0559b5c98a4311c7ec5427b5b788fee6333950832eb36f050e83b30661a0f354932482fded38972
@@ -70,6 +70,18 @@ PostHog::Rails.configure do |config|
70
70
  # Broadcast Rails.logger into PostHog Logs (default: true when logs enabled)
71
71
  # config.logs_forward_rails_logger = true
72
72
 
73
+ # Structured notification logs (default: []; requires logs_enabled).
74
+ # Select only installed components; this does not load optional Rails components.
75
+ # Set logs_forward_rails_logger = false to avoid also forwarding generic log lines.
76
+ # config.logs_notifications = [:action_controller, :active_record, :active_job, :action_mailer]
77
+ # SQL records are debug; other successful lifecycle events are info, failures error.
78
+ # Controller params and keyed job arguments respect Rails filter_parameters and
79
+ # are JSON strings in rails.params / rails.job.arguments (bounded to 10 KB).
80
+ # Custom filters see original key/value types; unsafe or oversized parameter
81
+ # trees are redacted as a whole, not truncated before filtering.
82
+ # Unkeyed job arguments are redacted. SQL text/binds, headers/cookies, mail
83
+ # recipients, subject and content are not collected by notification logging.
84
+
73
85
  # Minimum severity to forward; nil inherits Rails.logger's level (default: nil)
74
86
  # config.logs_level = :info
75
87
 
@@ -91,6 +91,11 @@ module PostHog
91
91
 
92
92
  private
93
93
 
94
+ # Completion notifications run after around_perform has restored the parent scope.
95
+ def posthog_logs_context
96
+ @posthog_execution_context || posthog_job_context
97
+ end
98
+
94
99
  def copy_posthog_ids(data)
95
100
  data = {} unless data.is_a?(Hash)
96
101
  %w[distinct_id session_id].each_with_object({}) do |key, result|
@@ -47,6 +47,11 @@ module PostHog
47
47
  # (only takes effect when {#logs_enabled} is true).
48
48
  attr_accessor :logs_forward_rails_logger
49
49
 
50
+ # @return [Array<Symbol>] Components whose notifications produce structured logs. Defaults to [].
51
+ # Supports :action_controller, :active_record, :active_job, and :action_mailer.
52
+ # Only takes effect when logs_enabled is true; components are not loaded automatically.
53
+ attr_accessor :logs_notifications
54
+
50
55
  # @return [Integer, Symbol, nil] Minimum severity to forward to PostHog Logs. When nil, inherits the
51
56
  # current Rails.logger level. Accepts a Logger severity constant (e.g. Logger::INFO) or symbol (:info).
52
57
  attr_accessor :logs_level
@@ -76,6 +81,7 @@ module PostHog
76
81
  @user_id_method = nil
77
82
  @logs_enabled = false
78
83
  @logs_forward_rails_logger = true
84
+ @logs_notifications = []
79
85
  @logs_level = nil
80
86
  @logs_max_records_per_minute = DEFAULT_LOGS_MAX_RECORDS_PER_MINUTE
81
87
  @logs_before_send = nil
@@ -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 if severity < @threshold
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 = apply_before_send(build_record(severity, message, progname))
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
@@ -2,6 +2,6 @@
2
2
 
3
3
  module PostHog
4
4
  module Rails
5
- VERSION = '3.22.0'
5
+ VERSION = '3.23.0'
6
6
  end
7
7
  end
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.22.0
4
+ version: 3.23.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - PostHog
@@ -55,6 +55,7 @@ files:
55
55
  - lib/posthog/rails/error_subscriber.rb
56
56
  - lib/posthog/rails/facade.rb
57
57
  - lib/posthog/rails/logs/appender.rb
58
+ - lib/posthog/rails/logs/notifications.rb
58
59
  - lib/posthog/rails/logs/rate_limiter.rb
59
60
  - lib/posthog/rails/logs/setup.rb
60
61
  - lib/posthog/rails/logs/severity.rb