Class: CwlogTail::CwClient

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

Constant Summary collapse

TAIL_INTERVAL =
5
DEFAULT_LINES =
100
DEFAULT_PAGE_COUNT =
3

Instance Method Summary collapse

Instance Method Details

#clientObject



9
10
11
# File 'lib/cwlog_tail/cw_client.rb', line 9

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

#log_group_namesObject



17
18
19
# File 'lib/cwlog_tail/cw_client.rb', line 17

def log_group_names
  log_groups.map(&:log_group_name)
end

#log_groupsObject



13
14
15
# File 'lib/cwlog_tail/cw_client.rb', line 13

def log_groups
  client.describe_log_groups.log_groups
end

#log_streams(log_group_name, page_count = DEFAULT_PAGE_COUNT) ⇒ Object



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

def log_streams(log_group_name, page_count = DEFAULT_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



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
60
61
# File 'lib/cwlog_tail/cw_client.rb', line 34

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 TAIL_INTERVAL
      else
        break
      end
    end
    last_token = pages.next_forward_token
  end
end