Class: Capsium::LogBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/capsium/log_buffer.rb,
sig/capsium/log_buffer.rbs

Overview

A small thread-safe ring buffer of timestamped log entries with a fixed capacity: when full, the oldest entry is dropped.

Defined Under Namespace

Classes: Entry

Constant Summary collapse

DEFAULT_CAPACITY =

Returns:

  • (Integer)
500

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity: DEFAULT_CAPACITY) ⇒ LogBuffer

Returns a new instance of LogBuffer.

Parameters:

  • capacity: (Integer capacity) (defaults to: DEFAULT_CAPACITY)

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
# File 'lib/capsium/log_buffer.rb', line 21

def initialize(capacity: DEFAULT_CAPACITY)
  raise ArgumentError, "capacity must be at least 1" if capacity < 1

  @capacity = capacity
  @entries = []
  @mutex = Mutex.new
end

Instance Attribute Details

#capacityInteger (readonly)

Returns the value of attribute capacity.

Returns:

  • (Integer)


19
20
21
# File 'lib/capsium/log_buffer.rb', line 19

def capacity
  @capacity
end

Instance Method Details

#add(message, timestamp: Time.now) ⇒ LogBuffer

Parameters:

  • message (String)
  • timestamp: (Time timestamp) (defaults to: Time.now)

Returns:



29
30
31
32
33
34
35
# File 'lib/capsium/log_buffer.rb', line 29

def add(message, timestamp: Time.now)
  @mutex.synchronize do
    @entries.shift if @entries.size >= @capacity
    @entries << Entry.new(timestamp: timestamp, message: message)
  end
  self
end

#last(count) ⇒ Array[Entry]

The last n entries, oldest first.

Parameters:

  • count (Integer)

Returns:



38
39
40
# File 'lib/capsium/log_buffer.rb', line 38

def last(count)
  @mutex.synchronize { @entries.last(count) }
end

#lines(count) ⇒ Array[String]

The last n entries as formatted lines, oldest first.

Parameters:

  • count (Integer)

Returns:

  • (Array[String])


43
44
45
# File 'lib/capsium/log_buffer.rb', line 43

def lines(count)
  last(count).map(&:line)
end