Class: Capsium::LogBuffer
- Inherits:
-
Object
- Object
- Capsium::LogBuffer
- 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 =
500
Instance Attribute Summary collapse
-
#capacity ⇒ Integer
readonly
Returns the value of attribute capacity.
Instance Method Summary collapse
- #add(message, timestamp: Time.now) ⇒ LogBuffer
-
#initialize(capacity: DEFAULT_CAPACITY) ⇒ LogBuffer
constructor
A new instance of LogBuffer.
-
#last(count) ⇒ Array[Entry]
The last n entries, oldest first.
-
#lines(count) ⇒ Array[String]
The last n entries as formatted lines, oldest first.
Constructor Details
#initialize(capacity: DEFAULT_CAPACITY) ⇒ LogBuffer
Returns a new instance of LogBuffer.
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
#capacity ⇒ Integer (readonly)
Returns the value of attribute capacity.
19 20 21 |
# File 'lib/capsium/log_buffer.rb', line 19 def capacity @capacity end |
Instance Method Details
#add(message, timestamp: Time.now) ⇒ LogBuffer
29 30 31 32 33 34 35 |
# File 'lib/capsium/log_buffer.rb', line 29 def add(, timestamp: Time.now) @mutex.synchronize do @entries.shift if @entries.size >= @capacity @entries << Entry.new(timestamp: , message: ) end self end |
#last(count) ⇒ Array[Entry]
The last n entries, oldest first.
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.
43 44 45 |
# File 'lib/capsium/log_buffer.rb', line 43 def lines(count) last(count).map(&:line) end |