Class: RailsErrorDashboard::Commands::LogError

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_error_dashboard/commands/log_error.rb

Overview

Command: Log an error to the database This is a write operation that creates an ErrorLog record

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(exception, context = {}) ⇒ LogError

Returns a new instance of LogError.



188
189
190
191
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 188

def initialize(exception, context = {})
  @exception = exception
  @context = context
end

Class Method Details

.build_capture_span_attributes(exception, was_async:) ⇒ Hash<String, Object>

Build the base OTel span attributes available before any work happens. Kept as a module-level helper so both sync and async paths can call it.

Returns:

  • (Hash<String, Object>)


67
68
69
70
71
72
73
74
75
76
77
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 67

def self.build_capture_span_attributes(exception, was_async:)
  msg = exception.message.to_s
  {
    "error.type" => exception.class.name,
    "error.message" => msg.length > 200 ? "#{msg[0, 200]}" : msg,
    "rails_error_dashboard.environment" => (defined?(Rails) && Rails.env.to_s) || "unknown",
    "rails_error_dashboard.was_async" => was_async
  }
rescue StandardError
  { "error.type" => "unknown", "rails_error_dashboard.was_async" => was_async }
end

.call(exception, context = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 8

def self.call(exception, context = {})
  # Filter FIRST (ignore list + static sampling) so ignored exceptions
  # never count toward storm state. _pre_filtered prevents the sync path
  # from re-rolling the sampling dice (rate would square otherwise).
  # The filter + gate run inside this method's rescue: nothing in the
  # capture path may ever raise into the host app.
  begin
    unless Services::ExceptionFilter.should_log?(exception)
      # Preserve the OTel contract: filtered captures still emit a span
      # tagged filtered=true (no-op when OTel export is disabled).
      Integrations::Tracer.in_span(
        "capture_error",
        kind: :capture,
        attributes: build_capture_span_attributes(exception, was_async: false)
      ) do |span|
        span&.set_attribute("rails_error_dashboard.filtered", true)
      end
      return nil
    end
    context = context.merge(_pre_filtered: true)

    # Storm protection gate — BEFORE the async branch, because with
    # SolidQueue the enqueue itself is a DB write. :count_only events are
    # tallied in memory and reconciled by StormFlushJob; nothing else
    # happens for them (that's the point).
    storm_decision = Services::StormProtection::Gate.admit!(exception, context)
    return nil if storm_decision == :count_only
    context = context.merge(_storm_decision: storm_decision) if storm_decision == :lite
  rescue => e
    RailsErrorDashboard::Logger.error(
      "[RailsErrorDashboard] Capture pre-checks failed: #{e.class} - #{e.message}"
    )
    # Fall through and attempt full capture — fail open, never raise
  end

  if RailsErrorDashboard.configuration.async_logging
    # For async logging, just enqueue the job
    call_async(exception, context)
  else
    # For sync logging, execute immediately
    new(exception, context).call
  end
rescue => e
  RailsErrorDashboard::Logger.error(
    "[RailsErrorDashboard] LogError.call failed: #{e.class} - #{e.message}"
  )
  nil
end

.call_async(exception, context = {}) ⇒ Object

Queue error logging as a background job



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 80

def self.call_async(exception, context = {})
  # Serialize exception data for the job
  exception_data = {
    class_name: exception.class.name,
    message: exception.message,
    backtrace: exception.backtrace,
    cause_chain: serialize_cause_chain(exception)
  }

  # Storm shedding: :lite captures skip ALL pre-enqueue context harvest —
  # this is request-thread CPU, the most valuable thing to shed.
  lite = storm_lite?(context)

  # Harvest breadcrumbs NOW (before job dispatch — different thread won't have them)
  if !lite && RailsErrorDashboard.configuration.enable_breadcrumbs
    context = context.merge(_serialized_breadcrumbs: Services::BreadcrumbCollector.harvest)
  end

  # Capture system health NOW (metrics are time-sensitive, different thread = different state)
  if !lite && RailsErrorDashboard.configuration.enable_system_health
    context = context.merge(_serialized_system_health: Services::SystemHealthSnapshot.capture)
  end

  # Capture local variables NOW (TracePoint attaches to exception, must extract before job dispatch)
  if !lite && RailsErrorDashboard.configuration.enable_local_variables
    begin
      raw_locals = Services::LocalVariableCapturer.extract(exception)
      if raw_locals.is_a?(Hash) && raw_locals.any?
        context = context.merge(_serialized_local_variables: Services::VariableSerializer.call(raw_locals))
      end
    rescue => e
      RailsErrorDashboard::Logger.debug("[RailsErrorDashboard] Async local variable serialization failed: #{e.message}")
    end
  end

  # Capture instance variables NOW (same reason — attached to exception object)
  if !lite && RailsErrorDashboard.configuration.enable_instance_variables
    begin
      raw_ivars = Services::LocalVariableCapturer.extract_instance_vars(exception)
      if raw_ivars.is_a?(Hash) && raw_ivars.any?
        context = context.merge(_serialized_instance_variables: Services::VariableSerializer.call(
          raw_ivars,
          max_count: RailsErrorDashboard.configuration.instance_variable_max_count,
          additional_filter_patterns: RailsErrorDashboard.configuration.instance_variable_filter_patterns
        ))
      end
    rescue => e
      RailsErrorDashboard::Logger.debug("[RailsErrorDashboard] Async instance variable serialization failed: #{e.message}")
    end
  end

  # Enqueue the async job using ActiveJob
  # The queue adapter (:sidekiq, :solid_queue, :async) is configured separately
  begin
    # OTel: emit a capture span around the enqueue itself. The real capture
    # work runs in the job (which starts its own root span via .new(...).call).
    # For the async path the span here measures *enqueue latency only* — used
    # to detect queue-adapter backpressure or Redis slowness.
    Integrations::Tracer.in_span(
      "capture_error",
      kind: :capture,
      attributes: build_capture_span_attributes(exception, was_async: true)
    ) do |_span|
      AsyncErrorLoggingJob.perform_later(exception_data, context)
    end
  rescue => e
    # Queue adapter failed (e.g., Redis down for Sidekiq). Fall back to
    # sync logging so the error is still captured. Without this rescue,
    # the exception propagates back to ErrorReporter, which re-reports it
    # via Rails.error.report → infinite recursion (issue #114).
    RailsErrorDashboard::Logger.error(
      "[RailsErrorDashboard] Async enqueue failed (#{e.class}: #{e.message}), falling back to sync logging"
    )
    new(exception, context).call
  end
end

.storm_lite?(context) ⇒ Boolean

:lite captures shed context (breadcrumbs/health/locals/ivars) — the storm shedding ladder’s first economy. Symbol or string key: the async job round-trips context through the queue serializer.

Returns:

  • (Boolean)


60
61
62
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 60

def self.storm_lite?(context)
  context[:_storm_decision].to_s == "lite"
end

Instance Method Details

#callObject



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 193

def call
  # OTel: parent capture span. Wraps the entire sync capture path so
  # operators can audit how long error capture takes from their existing
  # tracing pipeline. Child spans (breadcrumbs, health, notifications)
  # nest under this one automatically via OTel context propagation.
  #
  # The span lives INSIDE the rescue clause — if the span itself raises
  # somehow, the outer rescue still catches it and returns nil. Defense
  # in depth. When the block raises, the Tracer façade records the
  # exception on the span and re-raises so the rescue can swallow it.
  Integrations::Tracer.in_span(
    "capture_error",
    kind: :capture,
    attributes: self.class.build_capture_span_attributes(@exception, was_async: false)
  ) do |span|
  # Check if this exception should be logged (ignore list + sampling).
  # Skipped when self.call already filtered (re-rolling the sampling
  # dice here would square the effective rate).
  if !@context[:_pre_filtered] && !Services::ExceptionFilter.should_log?(@exception)
    span&.set_attribute("rails_error_dashboard.filtered", true)
    next nil
  end

  # Storm shedding: :lite captures keep the error + occurrence row but
  # shed context payloads (breadcrumbs/health/locals/ivars).
  storm_lite = self.class.storm_lite?(@context)
  span&.set_attribute("rails_error_dashboard.storm_degraded", true) if storm_lite

  error_context = ValueObjects::ErrorContext.new(@context, @context[:source])

  # Find or create application (cached lookup)
  application = find_or_create_application
  span&.set_attribute("rails_error_dashboard.application", application.name.to_s) if application.respond_to?(:name)

  # Build error attributes
  truncated_backtrace = Services::BacktraceProcessor.truncate(@exception.backtrace)
  attributes = {
    application_id: application.id,
    error_type: @exception.class.name,
    message: @exception.message,
    backtrace: truncated_backtrace,
    user_id: error_context.user_id,
    request_url: error_context.request_url,
    request_params: error_context.request_params,
    user_agent: error_context.user_agent,
    ip_address: error_context.ip_address,
    platform: error_context.platform,
    controller_name: error_context.controller_name,
    action_name: error_context.action_name,
    occurred_at: Time.current
  }

  # Enriched request context (if columns exist)
  enrich_with_request_context(attributes, error_context)

  # Extract exception cause chain (if column exists)
  if ErrorLog.column_names.include?("exception_cause")
    cause_json = Services::CauseChainExtractor.call(@exception)
    # Fall back to pre-serialized cause chain from async job context
    cause_json ||= build_cause_json_from_context
    attributes[:exception_cause] = cause_json
  end

  # Generate error hash for deduplication (including controller/action context and application)
  error_hash = Services::ErrorHashGenerator.call(
    @exception,
    controller_name: error_context.controller_name,
    action_name: error_context.action_name,
    application_id: application.id,
    context: @context
  )

  #  Calculate backtrace signature for fuzzy matching (if column exists)
  if ErrorLog.column_names.include?("backtrace_signature")
    attributes[:backtrace_signature] = Services::BacktraceProcessor.calculate_signature(
      truncated_backtrace,
      locations: @exception.backtrace_locations
    )
  end

  #  Add git/release info if columns exist
  if ErrorLog.column_names.include?("git_sha")
    attributes[:git_sha] = RailsErrorDashboard.configuration.git_sha ||
                            ENV["GIT_SHA"] ||
                            ENV["HEROKU_SLUG_COMMIT"] ||
                            ENV["RENDER_GIT_COMMIT"] ||
                            detect_git_sha_from_command
  end

  if ErrorLog.column_names.include?("app_version")
    attributes[:app_version] = RailsErrorDashboard.configuration.app_version ||
                                ENV["APP_VERSION"] ||
                                detect_version_from_file
  end

  # Add environment snapshot (if column exists)
  if ErrorLog.column_names.include?("environment_info")
    attributes[:environment_info] = Services::EnvironmentSnapshot.snapshot.to_json
  end

  # Apply sensitive data filtering (on by default)
  attributes = Services::SensitiveDataFilter.filter_attributes(attributes)

  # Harvest breadcrumbs (if enabled and column exists)
  if !storm_lite && ErrorLog.column_names.include?("breadcrumbs") && RailsErrorDashboard.configuration.enable_breadcrumbs
    # Sync path: harvest from current thread
    raw_breadcrumbs = Services::BreadcrumbCollector.harvest

    # Async path fallback: use pre-serialized breadcrumbs from call_async context
    if raw_breadcrumbs.empty?
      serialized = @context[:_serialized_breadcrumbs]
      raw_breadcrumbs = serialized if serialized.is_a?(Array)
    end

    if raw_breadcrumbs.is_a?(Array) && raw_breadcrumbs.any?
      filtered = Services::BreadcrumbCollector.filter_sensitive(raw_breadcrumbs)
      attributes[:breadcrumbs] = filtered.to_json
    end
  end

  # Capture system health snapshot (if enabled and column exists)
  if !storm_lite && ErrorLog.column_names.include?("system_health") && RailsErrorDashboard.configuration.enable_system_health
    health_data = @context[:_serialized_system_health] || Services::SystemHealthSnapshot.capture
    attributes[:system_health] = health_data.to_json
  end

  # Capture local variables (if enabled and column exists)
  if !storm_lite && ErrorLog.column_names.include?("local_variables") && RailsErrorDashboard.configuration.enable_local_variables
    begin
      # Sync path: extract from exception ivar
      raw_locals = Services::LocalVariableCapturer.extract(@exception)
      # Async path fallback: use pre-serialized locals from call_async context
      raw_locals ||= @context[:_serialized_local_variables]
      if raw_locals.is_a?(Hash) && raw_locals.any?
        serialized = raw_locals == @context[:_serialized_local_variables] ? raw_locals : Services::VariableSerializer.call(raw_locals)
        attributes[:local_variables] = serialized.to_json
      end
    rescue => e
      RailsErrorDashboard::Logger.debug("[RailsErrorDashboard] Local variable serialization failed: #{e.message}")
    end
  end

  # Capture instance variables (if enabled and column exists)
  if !storm_lite && ErrorLog.column_names.include?("instance_variables") && RailsErrorDashboard.configuration.enable_instance_variables
    begin
      # Sync path: extract from exception ivar
      raw_ivars = Services::LocalVariableCapturer.extract_instance_vars(@exception)
      # Async path fallback: use pre-serialized ivars from call_async context
      raw_ivars ||= @context[:_serialized_instance_variables]
      if raw_ivars.is_a?(Hash) && raw_ivars.any?
        serialized = if raw_ivars == @context[:_serialized_instance_variables]
          raw_ivars
        else
          Services::VariableSerializer.call(
            raw_ivars,
            max_count: RailsErrorDashboard.configuration.instance_variable_max_count,
            additional_filter_patterns: RailsErrorDashboard.configuration.instance_variable_filter_patterns
          )
        end
        attributes[:instance_variables] = serialized.to_json
      end
    rescue => e
      RailsErrorDashboard::Logger.debug("[RailsErrorDashboard] Instance variable serialization failed: #{e.message}")
    end
  end

  # Find existing error or create new one
  # This ensures accurate occurrence tracking
  error_log = ErrorLog.find_or_increment_by_hash(error_hash, attributes.merge(error_hash: error_hash))

  # OTel: now that the error_log exists, attach its id + dedup flag + severity
  # to the parent capture span so operators can correlate to dashboard URLs.
  if span && error_log
    span.set_attribute("rails_error_dashboard.error_id", error_log.id) if error_log.id
    span.set_attribute("rails_error_dashboard.deduplicated", error_log.occurrence_count.to_i > 1)
    span.set_attribute("rails_error_dashboard.severity", error_log.severity.to_s) if error_log.respond_to?(:severity) && error_log.severity
  end

  #  Track individual error occurrence for co-occurrence analysis (if table exists)
  if defined?(ErrorOccurrence) && ErrorOccurrence.table_exists?
    begin
      ErrorOccurrence.create(
        error_log: error_log,
        occurred_at: attributes[:occurred_at],
        user_id: attributes[:user_id],
        request_id: error_context.request_id,
        session_id: error_context.session_id
      )
    rescue => e
      RailsErrorDashboard::Logger.error("Failed to create error occurrence: #{e.message}")
    end
  end

  # Send notifications for new errors and reopened errors (with throttling).
  # Muted errors skip notification dispatch but still fire plugin events.
  if error_log.occurrence_count == 1
    maybe_notify(error_log) { Services::NotificationThrottler.severity_meets_minimum?(error_log) }
    PluginRegistry.dispatch(:on_error_logged, error_log)
    trigger_callbacks(error_log)
    emit_instrumentation_events(error_log)
  elsif error_log.just_reopened
    maybe_notify(error_log) { Services::NotificationThrottler.should_notify?(error_log) }
    PluginRegistry.dispatch(:on_error_reopened, error_log)
    trigger_callbacks(error_log)
    emit_instrumentation_events(error_log)
  else
    maybe_notify(error_log) { Services::NotificationThrottler.threshold_reached?(error_log) }
    PluginRegistry.dispatch(:on_error_recurred, error_log)
  end

  #  Check for baseline anomalies
  check_baseline_anomaly(error_log)

  error_log
  end
rescue => e
  # Don't let error logging cause more errors - fail silently
  # CRITICAL: Log but never propagate exception
  RailsErrorDashboard::Logger.error("[RailsErrorDashboard] LogError command failed: #{e.class} - #{e.message}")
  RailsErrorDashboard::Logger.error("Original exception: #{@exception.class} - #{@exception.message}") if @exception
  RailsErrorDashboard::Logger.error("Context: #{@context.inspect.truncate(500)}") if @context
  RailsErrorDashboard::Logger.error(e.backtrace&.first(5)&.join("\n")) if e.backtrace
  nil # Explicitly return nil, never raise
end