agent_log.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # AgentLogs are temporary records of Agent activity, intended for debugging and error tracking. They can be viewed
  2. # in Agents' detail pages. AgentLogs with a `level` of 4 or greater are considered "errors" and automatically update
  3. # Agents' `last_error_log_at` column. These are often used to determine if an Agent is `working?`.
  4. class AgentLog < ActiveRecord::Base
  5. attr_accessible :agent, :inbound_event, :level, :message, :outbound_event
  6. belongs_to :agent
  7. belongs_to :inbound_event, :class_name => "Event"
  8. belongs_to :outbound_event, :class_name => "Event"
  9. validates_presence_of :agent, :message
  10. validates_numericality_of :level, :only_integer => true, :greater_than_or_equal_to => 0, :less_than => 5
  11. before_validation :scrub_message
  12. before_save :truncate_message
  13. scope :errors, lambda { where('level > 3') }
  14. def self.log_for_agent(agent, message, options = {})
  15. puts "Agent##{agent.id}: #{message}" unless Rails.env.test?
  16. log = agent.logs.create! options.merge(:message => message)
  17. if agent.logs.count > log_length
  18. oldest_id_to_keep = agent.logs.limit(1).offset(log_length - 1).pluck("agent_logs.id")
  19. agent.logs.where("agent_logs.id < ?", oldest_id_to_keep).delete_all
  20. end
  21. agent.update_column :last_error_log_at, Time.now if log.level >= 4
  22. log
  23. end
  24. def self.log_length
  25. ENV['AGENT_LOG_LENGTH'].present? ? ENV['AGENT_LOG_LENGTH'].to_i : 200
  26. end
  27. protected
  28. def scrub_message
  29. if message_changed? && !message.nil?
  30. self.message = message.inspect unless message.is_a?(String)
  31. self.message.scrub!{ |bytes| "<#{bytes.unpack('H*')[0]}>" }
  32. end
  33. true
  34. end
  35. def truncate_message
  36. self.message = message[0...10_000] if message.present?
  37. end
  38. end