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(tags.merge(exception: err.class.name, message: err.message, trace: Array(err.backtrace)[0..9]))
end

#finishObject

Finish tracing, and flush storage.



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

def finish
  storage.async.flush
  @trace_id = nil
  @tags     = {}
end

#startObject

Create a new trace ID to link log entries.

Raises:



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

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)})
  @tags     = {} # This is used to accumulate tags in case we have an exception.
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:



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

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)

  # Include some standard tags.
  data[:environment]  ||= Trailer.config.environment
  data[:host_name]    ||= Trailer.config.host_name
  data[:service_name] ||= Trailer.config.service_name
  data                  = data.compact.merge(trace_id: trace_id)

  storage.async.write(data)
  @tags.merge!(data)
end