require 'json' module Logworm class LogwormException < Exception ; end class Logger # Initialize LW_SERVER = DB.from_config $lr_queue = [] def self.start_cycle $request_id = "#{Thread.current.object_id}-#{(Time.now.utc.to_f * 1000).to_i}" end def self.log(table, values = {}) begin # Rename conflicting keys kvalues = values.delete_if {|k,v| k.to_s == ""}.map {|k,v| [k.to_sym, v]} kvalues = Hash[*kvalues.flatten] [:_ts, :_ts_utc, :_request_id].each do |k| kvalues["orig_#{k}".to_sym] = kvalues[k] if kvalues.has_key? k end # Add information ts = Time.now.utc log_details = {:_ts => ts.strftime("%Y-%m-%dT%H:%M:%SZ"), :_ts_utc => (ts.to_f * 1000).to_i} log_details[:_request_id] = $request_id if $request_id # Enqueue payload = kvalues.merge(log_details) $lr_queue << [table, payload] rescue Exception => e $stderr.puts "Error in Logworm::Logger.log: #{e}" end end def self.flush to_send = $lr_queue.size return 0 if to_send == 0 unless LW_SERVER $stderr.puts "\t logworm not configured. #{to_send} entries dropped." $lr_queue = [] return 0 end begin LW_SERVER.batch_log($lr_queue.to_json) rescue Exception => e $stderr.puts "in Logworm::Logger.flush: #{e}" end $lr_queue = [] to_send end end end