Sha256: dd7a3cc435e94dfab1da164eddcee78f604678eac2f293f21eb0fa541ab54b5f

Contents?: true

Size: 1.41 KB

Versions: 1

Compression:

Stored size: 1.41 KB

Contents

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 
      $stderr.puts "Logworm not configured. #{$to_send} entries dropped." and return 0 unless LW_SERVER
      
      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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
logworm_client-0.5.0 lib/logworm_client/logger.rb