Class: ActiveSupport::BufferedLogger

Inherits:
Object
  • Object
show all
Includes:
Severity
Defined in:
lib/active_support/buffered_logger.rb

Overview

Inspired by the buffered logger idea by Ezra

Defined Under Namespace

Modules: Severity

Constant Summary collapse

MAX_BUFFER_SIZE =
1000

Constants included from Severity

Severity::DEBUG, Severity::ERROR, Severity::FATAL, Severity::INFO, Severity::UNKNOWN, Severity::WARN

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(log, level = DEBUG) ⇒ BufferedLogger

Returns a new instance of BufferedLogger.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/active_support/buffered_logger.rb', line 38

def initialize(log, level = DEBUG)
  @level         = level
  @buffer        = []
  @auto_flushing = 1

  if log.respond_to?(:write)
    @log = log
  elsif File.exist?(log)
    @log = open(log, (File::WRONLY | File::APPEND))
    @log.sync = true
  else
    @log = open(log, (File::WRONLY | File::APPEND | File::CREAT))
    @log.sync = true
    @log.write("# Logfile created on %s" % [Time.now.to_s])
  end
end

Instance Attribute Details

#auto_flushingObject

Returns the value of attribute auto_flushing.



35
36
37
# File 'lib/active_support/buffered_logger.rb', line 35

def auto_flushing
  @auto_flushing
end

#bufferObject (readonly)

Returns the value of attribute buffer.



36
37
38
# File 'lib/active_support/buffered_logger.rb', line 36

def buffer
  @buffer
end

#levelObject

Returns the value of attribute level.



34
35
36
# File 'lib/active_support/buffered_logger.rb', line 34

def level
  @level
end

Instance Method Details

#add(severity, message = nil, progname = nil, &block) ⇒ Object



55
56
57
58
59
60
61
62
63
64
# File 'lib/active_support/buffered_logger.rb', line 55

def add(severity, message = nil, progname = nil, &block)
  return if @level > severity
  message = (message || (block && block.call) || progname).to_s
  # If a newline is necessary then create a new message ending with a newline.
  # Ensures that the original message is not mutated.
  message = "#{message}\n" unless message[-1] == ?\n
  @buffer << message
  auto_flush
  message
end

#closeObject



96
97
98
99
100
# File 'lib/active_support/buffered_logger.rb', line 96

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

#flushObject



92
93
94
# File 'lib/active_support/buffered_logger.rb', line 92

def flush
  @log.write(@buffer.slice!(0..-1).join) unless @buffer.empty?
end

#silence(temporary_level = ERROR) ⇒ Object

Silences the logger for the duration of the block.



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_support/buffered_logger.rb', line 21

def silence(temporary_level = ERROR)
  if silencer
    begin
      old_logger_level, self.level = level, temporary_level
      yield self
    ensure
      self.level = old_logger_level
    end
  else
    yield self
  end
end