Sha256: 9ea885e69403e17ef91025ceee1261dfd37ae3661cc981014d541c4dccb573c0

Contents?: true

Size: 1.8 KB

Versions: 4

Compression:

Stored size: 1.8 KB

Contents

# This class can be used to build and execute queries. For example, the
# following code builds a query for 'error' in the last 15 minutes.
#
# q = Sumo::QueryBuilder.new('user@example.com:pass')
#         .query('error')
#         .from('-15m')
#         .to('now')
#
# Note that this class is immutable.
class Sumo::QueryBuilder
  include Sumo::Error

  attr_reader :creds, :opts

  # Create a new QueryBuilder with the given credentials and query.
  def initialize(creds, opts = {})
    if creds.is_a?(String) && opts.is_a?(Hash)
      @creds = creds.freeze
      @opts = opts.freeze
    else
      raise TypeError, "Invalid initialization parameters to QueryBuilder."
    end
  end

  # Metaprogram the #query, #to, #from, #time_zone, and #format methods. Each
  # of these methods accepts one argument, and returns a new 'QueryBuilder' that
  # has the specified query parameter key set.
  def self.builder(name, key)
    klass = self
    define_method(name) { |arg| klass.new(creds, opts.merge(key => arg)) }
  end
  private_class_method :builder

  builder :to, 'to'
  builder :from, 'from'
  builder :query, 'q'
  builder :format, 'format'
  builder :time_zone, 'tz'

  # Send the API request to Sumo Logic.
  def execute
    encoded = Base64.encode64(creds)
    resp = connection.get(:path => '/api/v1/logs/search',
                          :query => opts,
                          :headers => { 'Authorization' => "Basic #{encoded}" })
    if resp.status >= 400
      if resp.body.nil? || resp.body.empty?
        raise RequestError, "An error occurred sending your request."
      else
        raise RequestError, JSON.parse(resp.body)['message']
      end
    end
    resp.body
  end

  # A memoized HTTP connection.
  def connection
    @connection ||= Excon.new('https://api.sumologic.com')
  end
  private :connection
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
sumo-search-0.1.1 lib/sumo/query_builder.rb
sumo-search-0.1.0 lib/sumo/query_builder.rb
sumo-search-0.0.2 lib/sumo/query_builder.rb
sumo-search-0.0.1 lib/sumo/query_builder.rb