Class: Trailer::Recorder

Inherits:
Object
  • Object
show all
Defined in:
lib/trailer/recorder.rb

Instance Method Summary collapse

Constructor Details

#initialize(storage) ⇒ Recorder

Constructor.

Parameters:



8
9
10
# File 'lib/trailer/recorder.rb', line 8

def initialize(storage)
  @storage = storage
end

Instance Method Details

#add_exception(err) ⇒ Object

Records the exception class and message on the current trace.

Parameters:

  • err (Exception)

    The exception to record.



15
16
17
# File 'lib/trailer/recorder.rb', line 15

def add_exception(err)
  write({ exception: err.class.name, message: err.message, trace: err.backtrace[0..9] })
end

#finishObject

Finish tracing, and flush storage.



20
21
22
23
# File 'lib/trailer/recorder.rb', line 20

def finish
  storage.async.flush
  @trace_id = nil
end

#startObject

Create a new trace ID to link log entries.

Raises:



26
27
28
29
30
31
# File 'lib/trailer/recorder.rb', line 26

def start
  raise Trailer::Error, 'finish() must be called before a new trace can be started' unless @trace_id.nil?

  # See https://github.com/aws/aws-xray-sdk-ruby/blob/1869ca5/lib/aws-xray-sdk/model/segment.rb#L26-L30
  @trace_id = %(1-#{Time.now.to_i.to_s(16)}-#{SecureRandom.hex(12)})
end

#write(data) ⇒ Object

Write the given hash to storage.

Parameters:

  • data (Hash)

    A key-value hash of trace data to write to storage.

Raises:



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/trailer/recorder.rb', line 36

def write(data)
  raise Trailer::Error, 'start() must be called before write()' if @trace_id.nil?
  raise Trailer::Error, 'data must be an instance of Hash' unless data.is_a?(Hash)
  raise Trailer::Error, 'could not convert data to JSON' unless data.respond_to?(:to_json)

  # Include some standard tags.
  data[:environment]  ||= Trailer.config.environment
  data[:host_name]    ||= Trailer.config.host_name
  data[:service_name] ||= Trailer.config.service_name

  storage.async.write(data.compact.merge(trace_id: trace_id))
end