class Towel::Log

Constants

FLUSH_COUNT

How many log lines to send at a time. If there are more than this, they will be broken up into several `AppendLog` calls.

FLUSH_INTERVAL_SECONDS

How long to wait for more log entries before calling `AppendLog`. This tries to batch log lines together as opposed to making a call for each log line individually.

NAME_FORMAT

Logs must be associated with an invocation.

Attributes

name[R]

Public Class Methods

new(name, stub) click to toggle source
# File lib/towel/log.rb, line 17
def initialize(name, stub)
  unless name =~ NAME_FORMAT
    raise ArgumentError, "Log name #{name} is invalid"
  end
  raise ArgumentError, "Stub must be provided" unless stub
  @name = name
  @stub = stub
  @entries = Queue.new
  @entry_id = Concurrent::AtomicFixnum.new(-1)
  @flush_mutex = Mutex.new
  @flush_timer_mutex = Mutex.new
  @flush_timer = nil

  # Create the log
  log = Towel::V1alpha::Log.new
  log.name = @name
  request = Towel::V1alpha::CreateLogRequest.new
  request.log = log
  @stub.create_log(request)
end

Public Instance Methods

<<(line) click to toggle source
# File lib/towel/log.rb, line 46
def <<(line)
  entry = Towel::V1alpha::LogEntry.new
  entry.entry_id = @entry_id.increment
  entry.log_time = Time.now.utc
  entry.parent = context if context
  entry.contents = line

  @entries << entry

  # Set up a flush to happen momentarily, allowing other lines to possibly
  # be flushed together with this one.
  @flush_timer_mutex.synchronize do
    unless @flush_timer
      @flush_timer = Concurrent::ScheduledTask.execute(
        FLUSH_INTERVAL_SECONDS
      ) { flush }
    end
  end
end
close() click to toggle source
# File lib/towel/log.rb, line 66
def close
  flush
  Thread.current["towel_context_#{object_id}"] = nil
end
context() click to toggle source
# File lib/towel/log.rb, line 38
def context
  Thread.current["towel_context_#{object_id}"]
end
context=(context) click to toggle source
# File lib/towel/log.rb, line 42
def context=(context)
  Thread.current["towel_context_#{object_id}"] = context
end
flush() click to toggle source

Ensure that entries get written out to Towel.

# File lib/towel/log.rb, line 72
def flush
  @flush_mutex.synchronize do
    # Acknowledge the flush timer by unsetting it, if it exists.
    @flush_timer_mutex.synchronize do
      @flush_timer.cancel if @flush_timer
      @flush_timer = nil
    end

    until @entries.empty?
      request = Towel::V1alpha::AppendLogRequest.new
      request.name = @name
      i = 0
      while i < FLUSH_COUNT
        i += 1
        begin
          entry = @entries.pop(true)
        rescue ThreadError # Raised if the queue is empty
          break
        end
        request.entries << entry
      end
      @stub.append_log(request)
    end
  end
end