Module: BufferedLogger::Buffering

Included in:
BufferedLogger
Defined in:
lib/buffered_logger/buffering.rb

Constant Summary collapse

MAX_BUFFER_SIZE =
1000

Instance Method Summary collapse

Instance Method Details

#auto_flushingObject



16
17
18
# File 'lib/buffered_logger/buffering.rb', line 16

def auto_flushing
  @auto_flushing[Thread.current] || @auto_flushing[master_thread]
end

#auto_flushing=(period) ⇒ Object

Set the auto-flush period. Set to true to flush after every log message, to an integer to flush every N messages, or to false, nil, or zero to never auto-flush. If you turn auto-flushing off, be sure to regularly flush the log yourself – it will eat up memory until you do.



24
25
26
27
28
29
30
31
32
# File 'lib/buffered_logger/buffering.rb', line 24

def auto_flushing=(period)
  @auto_flushing[Thread.current] =
    case period
    when true;                1
    when false, nil, 0;       MAX_BUFFER_SIZE
    when Integer;             period
    else raise ArgumentError, "Unrecognized auto_flushing period: #{period.inspect}"
    end
end

#buffer_textObject



12
13
14
# File 'lib/buffered_logger/buffering.rb', line 12

def buffer_text
  buffer.join('')
end

#closeObject



46
47
48
49
50
# File 'lib/buffered_logger/buffering.rb', line 46

def close
  flush
  @log.close if @log.respond_to?(:close)
  @log = nil
end

#flushObject



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/buffered_logger/buffering.rb', line 34

def flush
  @guard.synchronize do
    buffer.each do |content|
      @log.write(content)
    end

    # Important to do this even if buffer was empty or else @buffer will
    # accumulate empty arrays for each request where nothing was logged.
    clear_buffer
  end
end

#initializeObject



4
5
6
7
8
9
10
# File 'lib/buffered_logger/buffering.rb', line 4

def initialize
  @buffer        = Hash.new { |h,k| h[k] = [] }
  @auto_flushing = BufferedLogger::ThreadHash.new
  @auto_flushing[master_thread] = 1
  @guard = Mutex.new
  super()
end