Sha256: eeca2f4949bff8313b1973123ab5e81ab3382864b05f65fc6c3f978306f5b585

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module Justlogging

  class Agent

    attr_reader :queue, :active, :sleep_time

    def initialize
      @sleep_time = 5
      @queue = []
      @active = true
      @thread = Thread.new do
        while true do
          if (@queue.any? && @active == true)
            send_queue
          end
          sleep @sleep_time
        end
      end
    end

    def add_to_queue(transaction)
      @queue << transaction
    end

    def uri
      URI(Justlogging.config[:endpoint])
    end

    def http_client
      Net::HTTP.new(uri.host, uri.port).tap do |http|
        if uri.scheme == 'https'
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_PEER
        end
      end
    end

    def send_queue
      json = ActiveSupport::JSON.encode @queue
      request = Net::HTTP::Post.new(uri.request_uri)
      request.set_form_data('api_key' => Justlogging.config[:api_key], 'log_entries' => json)

      begin
        result = http_client.request(request)
        code = result.code
      rescue => error
        code = nil
      end
      handle_result(code)
    end

    # Empty queue is result is 200 ok.
    # Throttle connection when result is 403
    # Unsubscribe and stop sending all together on any other code.
    def handle_result(code)
      if code == '200'
        @queue = []
      elsif code == '403'
        @sleep_time = @sleep_time * 1.5
      else
        ActiveSupport::Notifications.unsubscribe(Justlogging.subscriber)
        @active = false
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
justlogging-rails-0.0.5 lib/justlogging/agent.rb