Class: CwlogTail::CwClient

Inherits:
Object
  • Object
show all
Defined in:
lib/cwlog_tail/cw_client.rb

Constant Summary collapse

DEFAULT_LINES =
100

Instance Method Summary collapse

Instance Method Details

#clientObject



7
8
9
# File 'lib/cwlog_tail/cw_client.rb', line 7

def client
  @cloudwatch ||= Aws::CloudWatchLogs::Client.new
end

#log_group_namesObject



15
16
17
# File 'lib/cwlog_tail/cw_client.rb', line 15

def log_group_names
  log_groups.map(&:log_group_name)
end

#log_groupsObject



11
12
13
# File 'lib/cwlog_tail/cw_client.rb', line 11

def log_groups
  client.describe_log_groups.each_page.to_a.map(&:log_groups).flatten
end

#log_streams(log_group_name, page_count) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/cwlog_tail/cw_client.rb', line 19

def log_streams(log_group_name, page_count)
  next_token = nil
  @log_streams ||= page_count.times.each.with_object([]) { |_, results|
    log_streams = client.describe_log_streams(
      log_group_name: log_group_name,
      order_by: :LastEventTime,
      descending: true,
      next_token: next_token)
    results << log_streams.log_streams
    next_token = log_streams.next_token
  }.flatten
end

#tail_stream(log_group_name, log_stream_name, options) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/cwlog_tail/cw_client.rb', line 32

def tail_stream(log_group_name, log_stream_name, options)
  last_token = nil
  loop do
    log_options = {
      log_group_name: log_group_name,
      log_stream_name: log_stream_name,
      next_token: last_token
    }
    if options.lines.nil?
      log_options[:start_from_head] = true
      log_options[:limit] = DEFAULT_LINES
    else
      log_options[:start_from_head] = false
      log_options[:limit] = options.lines
    end
    pages = client.get_log_events(log_options)
    pages.events.each { |event| yield(event) }

    if last_token == pages.next_forward_token
      if options.follow?
        sleep options.interval
      else
        break
      end
    end
    last_token = pages.next_forward_token
  end
end