Class: RailsErrorDashboard::ErrorLog
- Inherits:
-
ErrorLogsRecord
- Object
- ActiveRecord::Base
- ErrorLogsRecord
- RailsErrorDashboard::ErrorLog
- Defined in:
- app/models/rails_error_dashboard/error_log.rb
Constant Summary collapse
- CRITICAL_ERROR_TYPES =
%w[ SecurityError NoMemoryError SystemStackError SignalException ActiveRecord::StatementInvalid ].freeze
- HIGH_SEVERITY_ERROR_TYPES =
%w[ ActiveRecord::RecordNotFound ArgumentError TypeError NoMethodError NameError ].freeze
- MEDIUM_SEVERITY_ERROR_TYPES =
%w[ ActiveRecord::RecordInvalid Timeout::Error Net::ReadTimeout Net::OpenTimeout ].freeze
Class Method Summary collapse
-
.belongs_to(*args, **options) ⇒ Object
Override user association to use configured user model.
-
.find_or_increment_by_hash(error_hash, attributes = {}) ⇒ Object
Find existing error by hash or create new one This is CRITICAL for accurate occurrence tracking.
-
.log_error(exception, context = {}) ⇒ Object
Log an error with context (delegates to Command).
-
.statistics(days = 7) ⇒ Object
Get error statistics.
Instance Method Summary collapse
-
#backtrace_frames ⇒ Object
Extract backtrace frames for similarity comparison.
-
#baseline_anomaly(sensitivity: 2) ⇒ Hash
Check if this error is anomalous compared to baseline.
-
#baselines ⇒ Hash
Get baseline statistics for this error type.
-
#calculate_backtrace_signature ⇒ Object
Calculate backtrace signature for fast similarity matching Signature is a hash of the unique file paths in the backtrace.
- #calculate_priority_score ⇒ Object
-
#co_occurring_errors(window_minutes: 5, min_frequency: 2, limit: 10) ⇒ Array<Hash>
Find errors that occur together in time.
-
#critical? ⇒ Boolean
Check if this is a critical error.
-
#error_bursts(days: 7) ⇒ Array<Hash>
Detect error bursts (many errors in short time).
-
#error_cascades(min_probability: 0.5) ⇒ Hash
Find cascade patterns (what causes this error, what this error causes).
-
#generate_error_hash ⇒ Object
Generate unique hash for error grouping Includes controller/action for better context-aware grouping.
-
#occurrence_pattern(days: 30) ⇒ Hash
Detect cyclical occurrence patterns (daily/weekly rhythms).
-
#recent? ⇒ Boolean
Check if error is recent (< 1 hour).
-
#related_errors(limit: 5) ⇒ Object
Find related errors of the same type.
-
#resolve!(resolution_data = {}) ⇒ Object
Mark error as resolved (delegates to Command).
- #set_defaults ⇒ Object
- #set_release_info ⇒ Object
- #set_tracking_fields ⇒ Object
-
#severity ⇒ Object
Get severity level Checks custom severity rules first, then falls back to default classification.
-
#similar_errors(threshold: 0.6, limit: 10) ⇒ Array<Hash>
Find similar errors using fuzzy matching.
-
#stale? ⇒ Boolean
Check if error is old unresolved (> 7 days).
Class Method Details
.belongs_to(*args, **options) ⇒ Object
Override user association to use configured user model
348 349 350 351 352 353 354 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 348 def self.belongs_to(*args, **) if args.first == :user user_model = RailsErrorDashboard.configuration.user_model [:class_name] = user_model if user_model.present? end super end |
.find_or_increment_by_hash(error_hash, attributes = {}) ⇒ Object
Find existing error by hash or create new one This is CRITICAL for accurate occurrence tracking
143 144 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 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 143 def self.find_or_increment_by_hash(error_hash, attributes = {}) # Look for unresolved error with same hash in last 24 hours # (resolved errors are considered "fixed" so new occurrence = new issue) existing = unresolved .where(error_hash: error_hash) .where("occurred_at >= ?", 24.hours.ago) .order(last_seen_at: :desc) .first if existing # Increment existing error existing.update!( occurrence_count: existing.occurrence_count + 1, last_seen_at: Time.current, # Update context from latest occurrence user_id: attributes[:user_id] || existing.user_id, request_url: attributes[:request_url] || existing.request_url, request_params: attributes[:request_params] || existing.request_params, user_agent: attributes[:user_agent] || existing.user_agent, ip_address: attributes[:ip_address] || existing.ip_address ) existing else # Create new error record # Ensure resolved has a value (default to false) create!(attributes.reverse_merge(resolved: false)) end end |
.log_error(exception, context = {}) ⇒ Object
Log an error with context (delegates to Command)
173 174 175 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 173 def self.log_error(exception, context = {}) Commands::LogError.call(exception, context) end |
.statistics(days = 7) ⇒ Object
Get error statistics
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 183 def self.statistics(days = 7) start_date = days.days.ago { total: where("occurred_at >= ?", start_date).count, unresolved: where("occurred_at >= ?", start_date).unresolved.count, by_type: where("occurred_at >= ?", start_date) .group(:error_type) .count .sort_by { |_, count| -count } .to_h, by_day: where("occurred_at >= ?", start_date) .group("DATE(occurred_at)") .count } end |
Instance Method Details
#backtrace_frames ⇒ Object
Extract backtrace frames for similarity comparison
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 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 209 def backtrace_frames return [] if backtrace.blank? # Handle different backtrace formats lines = if backtrace.is_a?(Array) backtrace elsif backtrace.is_a?(String) # Check if it's a serialized array (starts with "[") if backtrace.strip.start_with?("[") # Try to parse as JSON array begin JSON.parse(backtrace) rescue JSON::ParserError # Fall back to newline split backtrace.split("\n") end else backtrace.split("\n") end else [] end lines.first(20).map do |line| # Extract file path and method name, ignore line numbers if line =~ %r{([^/]+\.rb):.*?in `(.+)'$} "#{Regexp.last_match(1)}:#{Regexp.last_match(2)}" elsif line =~ %r{([^/]+\.rb)} Regexp.last_match(1) end end.compact.uniq end |
#baseline_anomaly(sensitivity: 2) ⇒ Hash
Check if this error is anomalous compared to baseline
304 305 306 307 308 309 310 311 312 313 314 315 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 304 def baseline_anomaly(sensitivity: 2) return { anomaly: false, message: "Feature disabled" } unless RailsErrorDashboard.configuration.enable_baseline_alerts return { anomaly: false, message: "No baseline available" } unless defined?(Queries::BaselineStats) # Get count of this error type today today_count = ErrorLog.where( error_type: error_type, platform: platform ).where("occurred_at >= ?", Time.current.beginning_of_day).count Queries::BaselineStats.new(error_type, platform).check_anomaly(today_count, sensitivity: sensitivity) end |
#baselines ⇒ Hash
Get baseline statistics for this error type
294 295 296 297 298 299 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 294 def baselines return {} unless RailsErrorDashboard.configuration.enable_baseline_alerts return {} unless defined?(Queries::BaselineStats) Queries::BaselineStats.new(error_type, platform).all_baselines end |
#calculate_backtrace_signature ⇒ Object
Calculate backtrace signature for fast similarity matching Signature is a hash of the unique file paths in the backtrace
244 245 246 247 248 249 250 251 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 244 def calculate_backtrace_signature frames = backtrace_frames return nil if frames.empty? # Create signature from sorted file paths (order-independent) file_paths = frames.map { |frame| frame.split(":").first }.sort Digest::SHA256.hexdigest(file_paths.join("|"))[0..15] end |
#calculate_priority_score ⇒ Object
68 69 70 71 72 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 68 def calculate_priority_score return unless respond_to?(:priority_score=) self.priority_score = compute_priority_score save if persisted? end |
#co_occurring_errors(window_minutes: 5, min_frequency: 2, limit: 10) ⇒ Array<Hash>
Find errors that occur together in time
268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 268 def co_occurring_errors(window_minutes: 5, min_frequency: 2, limit: 10) return [] unless persisted? return [] unless RailsErrorDashboard.configuration.enable_co_occurring_errors return [] unless defined?(Queries::CoOccurringErrors) Queries::CoOccurringErrors.call( error_log_id: id, window_minutes: window_minutes, min_frequency: min_frequency, limit: limit ) end |
#critical? ⇒ Boolean
Check if this is a critical error
90 91 92 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 90 def critical? CRITICAL_ERROR_TYPES.include?(error_type) end |
#error_bursts(days: 7) ⇒ Array<Hash>
Detect error bursts (many errors in short time)
334 335 336 337 338 339 340 341 342 343 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 334 def error_bursts(days: 7) return [] unless RailsErrorDashboard.configuration.enable_occurrence_patterns return [] unless defined?(Services::PatternDetector) Services::PatternDetector.detect_bursts( error_type: error_type, platform: platform, days: days ) end |
#error_cascades(min_probability: 0.5) ⇒ Hash
Find cascade patterns (what causes this error, what this error causes)
284 285 286 287 288 289 290 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 284 def error_cascades(min_probability: 0.5) return { parents: [], children: [] } unless persisted? return { parents: [], children: [] } unless RailsErrorDashboard.configuration.enable_error_cascades return { parents: [], children: [] } unless defined?(Queries::ErrorCascades) Queries::ErrorCascades.call(error_id: id, min_probability: min_probability) end |
#generate_error_hash ⇒ Object
Generate unique hash for error grouping Includes controller/action for better context-aware grouping
76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 76 def generate_error_hash # Hash based on error class, normalized message, first stack frame, controller, and action digest_input = [ error_type, &.gsub(/\d+/, "N")&.gsub(/"[^"]*"/, '""'), # Normalize numbers and strings backtrace&.lines&.first&.split(":")&.first, # Just the file, not line number controller_name, # Controller context action_name # Action context ].compact.join("|") Digest::SHA256.hexdigest(digest_input)[0..15] end |
#occurrence_pattern(days: 30) ⇒ Hash
Detect cyclical occurrence patterns (daily/weekly rhythms)
320 321 322 323 324 325 326 327 328 329 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 320 def occurrence_pattern(days: 30) return {} unless RailsErrorDashboard.configuration.enable_occurrence_patterns return {} unless defined?(Services::PatternDetector) Services::PatternDetector.analyze_cyclical_pattern( error_type: error_type, platform: platform, days: days ) end |
#recent? ⇒ Boolean
Check if error is recent (< 1 hour)
95 96 97 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 95 def recent? occurred_at >= 1.hour.ago end |
#related_errors(limit: 5) ⇒ Object
Find related errors of the same type
201 202 203 204 205 206 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 201 def (limit: 5) self.class.where(error_type: error_type) .where.not(id: id) .order(occurred_at: :desc) .limit(limit) end |
#resolve!(resolution_data = {}) ⇒ Object
Mark error as resolved (delegates to Command)
178 179 180 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 178 def resolve!(resolution_data = {}) Commands::ResolveError.call(id, resolution_data) end |
#set_defaults ⇒ Object
51 52 53 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 51 def set_defaults self.platform ||= "API" end |
#set_release_info ⇒ Object
62 63 64 65 66 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 62 def set_release_info return unless respond_to?(:app_version=) self.app_version ||= fetch_app_version self.git_sha ||= fetch_git_sha end |
#set_tracking_fields ⇒ Object
55 56 57 58 59 60 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 55 def set_tracking_fields self.error_hash ||= generate_error_hash self.first_seen_at ||= Time.current self.last_seen_at ||= Time.current self.occurrence_count ||= 1 end |
#severity ⇒ Object
Get severity level Checks custom severity rules first, then falls back to default classification
106 107 108 109 110 111 112 113 114 115 116 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 106 def severity # Check custom severity rules first custom_severity = RailsErrorDashboard.configuration.custom_severity_rules[error_type] return custom_severity.to_sym if custom_severity.present? # Fall back to default classification return :critical if CRITICAL_ERROR_TYPES.include?(error_type) return :high if HIGH_SEVERITY_ERROR_TYPES.include?(error_type) return :medium if MEDIUM_SEVERITY_ERROR_TYPES.include?(error_type) :low end |
#similar_errors(threshold: 0.6, limit: 10) ⇒ Array<Hash>
Find similar errors using fuzzy matching
257 258 259 260 261 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 257 def similar_errors(threshold: 0.6, limit: 10) return [] unless persisted? return [] unless RailsErrorDashboard.configuration.enable_similar_errors Queries::SimilarErrors.call(id, threshold: threshold, limit: limit) end |
#stale? ⇒ Boolean
Check if error is old unresolved (> 7 days)
100 101 102 |
# File 'app/models/rails_error_dashboard/error_log.rb', line 100 def stale? !resolved? && occurred_at < 7.days.ago end |