discourse/app/models/error_log.rb

94 lines
2.3 KiB
Ruby
Raw Normal View History

2013-02-07 23:45:24 +08:00
# TODO:
2013-02-06 03:16:51 +08:00
# a mechanism to iterate through errors in reverse
# async logging should queue, if dupe stack traces are found in batch error should be merged into prev one
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
class ErrorLog
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
@lock = Mutex.new
def self.filename
"#{Rails.root}/log/#{Rails.env}_errors.log"
end
2014-08-21 02:14:19 +08:00
def self.clear!(_guid)
raise NotImplementedError
2013-02-06 03:16:51 +08:00
end
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
def self.clear_all!()
File.delete(ErrorLog.filename) if File.exists?(ErrorLog.filename)
end
2013-02-07 23:45:24 +08:00
def self.report_async!(exception, controller, request, user)
2013-02-06 03:16:51 +08:00
Thread.new do
report!(exception, controller, request, user)
2013-02-06 03:16:51 +08:00
end
end
2013-02-07 23:45:24 +08:00
def self.report!(exception, controller, request, user)
2013-02-06 03:16:51 +08:00
add_row!(
date: DateTime.now,
guid: SecureRandom.uuid,
user_id: user && user.id,
2013-10-13 05:07:09 +08:00
parameters: request && request.filtered_parameters.to_json,
action: controller.action_name,
controller: controller.controller_name,
backtrace: sanitize_backtrace(exception.backtrace).join("\n"),
message: exception.message,
url: "#{request.protocol}#{request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]}#{request.fullpath}",
exception_class: exception.class.to_s
2013-02-06 03:16:51 +08:00
)
end
2013-02-07 23:45:24 +08:00
2013-02-06 03:16:51 +08:00
def self.add_row!(hash)
data = hash.to_xml(skip_instruct: true)
# use background thread to write the log cause it may block if it gets backed up
2013-02-07 23:45:24 +08:00
@lock.synchronize do
File.open(filename, "a") do |f|
2013-02-06 03:16:51 +08:00
f.flock(File::LOCK_EX)
f.write(data)
f.close
end
end
end
def self.each(&blk)
skip(0, &blk)
2013-02-06 03:16:51 +08:00
end
def self.skip(skip=0)
pos = 0
return [] unless File.exists?(filename)
2013-02-06 03:16:51 +08:00
2013-02-07 23:45:24 +08:00
loop do
2013-02-06 03:16:51 +08:00
lines = ""
File.open(self.filename, "r") do |f|
f.flock(File::LOCK_SH)
f.pos = pos
while !f.eof?
line = f.readline
lines << line
2013-02-07 23:45:24 +08:00
break if line.starts_with? "</hash>"
2013-02-06 03:16:51 +08:00
end
pos = f.pos
end
if lines != "" && skip == 0
h = {}
2013-02-07 23:45:24 +08:00
e = Nokogiri.parse(lines).children[0]
2013-02-06 03:16:51 +08:00
e.children.each do |inner|
h[inner.name] = inner.text
end
yield h
end
skip-=1 if skip > 0
break if lines == ""
2013-02-07 23:45:24 +08:00
end
2013-02-06 03:16:51 +08:00
end
def self.sanitize_backtrace(trace)
re = Regexp.new(/^#{Regexp.escape(Rails.root.to_s)}/)
trace.map { |line| Pathname.new(line.gsub(re, "[RAILS_ROOT]")).cleanpath.to_s }
end
end