Class: RailsErrorDashboard::Commands::LogError
- Inherits:
-
Object
- Object
- RailsErrorDashboard::Commands::LogError
- 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
-
.build_capture_span_attributes(exception, was_async:) ⇒ Hash<String, Object>
Build the base OTel span attributes available before any work happens.
- .call(exception, context = {}) ⇒ Object
-
.call_async(exception, context = {}) ⇒ Object
Queue error logging as a background job.
Instance Method Summary collapse
- #call ⇒ Object
-
#initialize(exception, context = {}) ⇒ LogError
constructor
A new instance of LogError.
Constructor Details
#initialize(exception, context = {}) ⇒ LogError
Returns a new instance of LogError.
140 141 142 143 |
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 140 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.
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 23 def self.build_capture_span_attributes(exception, was_async:) msg = exception..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 |
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 8 def self.call(exception, context = {}) # Check if async logging is enabled if RailsErrorDashboard.configuration.async_logging # For async logging, just enqueue the job # All filtering happens when the job runs call_async(exception, context) else # For sync logging, execute immediately new(exception, context).call end end |
.call_async(exception, context = {}) ⇒ Object
Queue error logging as a background job
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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 |
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 36 def self.call_async(exception, context = {}) # Serialize exception data for the job exception_data = { class_name: exception.class.name, message: exception., backtrace: exception.backtrace, cause_chain: serialize_cause_chain(exception) } # Harvest breadcrumbs NOW (before job dispatch — different thread won't have them) if RailsErrorDashboard.configuration. context = context.merge(_serialized_breadcrumbs: Services::BreadcrumbCollector.harvest) end # Capture system health NOW (metrics are time-sensitive, different thread = different state) if 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 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.}") end end # Capture instance variables NOW (same reason — attached to exception object) if 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.}") 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.}), falling back to sync logging" ) new(exception, context).call end end |
Instance Method Details
#call ⇒ Object
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 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 |
# File 'lib/rails_error_dashboard/commands/log_error.rb', line 145 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) if !Services::ExceptionFilter.should_log?(@exception) span&.set_attribute("rails_error_dashboard.filtered", true) next nil end 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., 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 ErrorLog.column_names.include?("breadcrumbs") && RailsErrorDashboard.configuration. # Sync path: harvest from current thread = Services::BreadcrumbCollector.harvest # Async path fallback: use pre-serialized breadcrumbs from call_async context if .empty? serialized = @context[:_serialized_breadcrumbs] = serialized if serialized.is_a?(Array) end if .is_a?(Array) && .any? filtered = Services::BreadcrumbCollector.filter_sensitive() attributes[:breadcrumbs] = filtered.to_json end end # Capture system health snapshot (if enabled and column exists) if 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 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.}") end end # Capture instance variables (if enabled and column exists) if 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.}") 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.}") 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.}") RailsErrorDashboard::Logger.error("Original exception: #{@exception.class} - #{@exception.}") 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 |