Class: Lumberjack::Device::Buffer::EntryBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/lumberjack/device/buffer.rb

Overview

Internal class that manages the entry buffer and flushing logic.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(device, size, before_flush) ⇒ EntryBuffer

Returns a new instance of EntryBuffer.



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/lumberjack/device/buffer.rb', line 23

def initialize(device, size, before_flush)
  @device = device
  @size = size
  @before_flush = before_flush if before_flush.respond_to?(:call)
  @before_flush_guard = :"lumberjack_device_buffer_before_flush_#{object_id}"
  @lock = Mutex.new
  @flush_lock = Mutex.new
  @entries = []
  @last_flushed_at = Time.now
  @closed = false
end

Instance Attribute Details

#deviceObject (readonly)

Returns the value of attribute device.



21
22
23
# File 'lib/lumberjack/device/buffer.rb', line 21

def device
  @device
end

#sizeObject

Returns the value of attribute size.



19
20
21
# File 'lib/lumberjack/device/buffer.rb', line 19

def size
  @size
end

Instance Method Details

#<<(entry) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/lumberjack/device/buffer.rb', line 35

def <<(entry)
  flush_needed = false

  @lock.synchronize do
    unless @closed
      @entries << entry
      flush_needed = @entries.size >= @size
    end
  end

  flush if flush_needed
end

#closeObject



71
72
73
74
# File 'lib/lumberjack/device/buffer.rb', line 71

def close
  @lock.synchronize { @closed = true }
  flush
end

#closed?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/lumberjack/device/buffer.rb', line 76

def closed?
  @lock.synchronize { @closed }
end

#empty?Boolean

Returns:

  • (Boolean)


84
85
86
# File 'lib/lumberjack/device/buffer.rb', line 84

def empty?
  @lock.synchronize { @entries.empty? }
end

#flushObject

Concurrent flushes are serialized by a separate lock so that batches cannot be interleaved or reordered when written to the wrapped device. The entry lock is only held while swapping out the buffered entries so that threads writing new entries are not blocked while the wrapped device performs I/O.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/lumberjack/device/buffer.rb', line 52

def flush
  call_before_flush

  @flush_lock.synchronize do
    entries = nil
    @lock.synchronize do
      entries = @entries
      @entries = []
      @last_flushed_at = Time.now
    end

    entries.each do |entry|
      @device.write(entry)
    rescue => e
      warn("Error writing log entry from buffer: #{e.inspect}")
    end
  end
end

#last_flushed_atObject



88
89
90
# File 'lib/lumberjack/device/buffer.rb', line 88

def last_flushed_at
  @lock.synchronize { @last_flushed_at }
end

#reopenObject



80
81
82
# File 'lib/lumberjack/device/buffer.rb', line 80

def reopen
  @lock.synchronize { @closed = false }
end