Class: Legion::Logging::AsyncWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/legion/logging/async_writer.rb

Defined Under Namespace

Classes: LogEntry

Constant Summary collapse

SHUTDOWN =
:shutdown

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger, buffer_size: 10_000) ⇒ AsyncWriter

Returns a new instance of AsyncWriter.



13
14
15
16
17
18
19
20
# File 'lib/legion/logging/async_writer.rb', line 13

def initialize(logger, buffer_size: 10_000)
  @logger = logger
  @buffer_size = buffer_size
  @queue  = SizedQueue.new(buffer_size)
  @thread = nil
  @state_mutex = Mutex.new
  @accepting = true
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



11
12
13
# File 'lib/legion/logging/async_writer.rb', line 11

def logger
  @logger
end

Instance Method Details

#alive?Boolean

rubocop:enable Naming/PredicateMethod

Returns:

  • (Boolean)


61
62
63
# File 'lib/legion/logging/async_writer.rb', line 61

def alive?
  @thread&.alive? || false
end

#push(entry) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/legion/logging/async_writer.rb', line 51

def push(entry)
  return false unless accepting?

  @queue.push(entry)
  true
rescue ClosedQueueError
  false
end

#startObject



22
23
24
25
26
27
28
29
30
31
# File 'lib/legion/logging/async_writer.rb', line 22

def start
  return if @thread&.alive?

  @state_mutex.synchronize { @accepting = true }
  drain
  @queue = SizedQueue.new(@buffer_size)
  @thread = Thread.new { consume }
  @thread.name = 'legion-log-writer'
  @thread.abort_on_exception = false
end

#stop(timeout: 2) ⇒ Object

rubocop:disable Naming/PredicateMethod



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/legion/logging/async_writer.rb', line 34

def stop(timeout: 2)
  @state_mutex.synchronize { @accepting = false }

  unless @thread&.alive?
    drain
    @thread = nil
    return true
  end

  @queue.close
  timeout ? @thread.join(timeout) : @thread.join
  return false if @thread&.alive?

  @thread = nil
  true
end