2 # Inspired by the buffered logger idea by Ezra
14 MAX_BUFFER_SIZE = 1000
16 # Set to false to disable the silencer
17 cattr_accessor :silencer
20 # Silences the logger for the duration of the block.
21 def silence(temporary_level = ERROR)
24 old_logger_level, self.level = level, temporary_level
27 self.level = old_logger_level
35 attr_reader :auto_flushing
38 def initialize(log, level = DEBUG)
43 if log.respond_to?(:write)
45 elsif File.exist?(log)
46 @log = open(log, (File::WRONLY | File::APPEND))
49 @log = open(log, (File::WRONLY | File::APPEND | File::CREAT))
51 @log.write("# Logfile created on %s" % [Time.now.to_s])
55 def add(severity, message = nil, progname = nil, &block)
56 return if @level > severity
57 message = (message || (block && block.call) || progname).to_s
58 # If a newline is necessary then create a new message ending with a newline.
59 # Ensures that the original message is not mutated.
60 message = "#{message}\n" unless message[-1] == ?\n
66 for severity in Severity.constants
67 class_eval <<-EOT, __FILE__, __LINE__
68 def #{severity.downcase}(message = nil, progname = nil, &block)
69 add(#{severity}, message, progname, &block)
72 def #{severity.downcase}?
78 # Set the auto-flush period. Set to true to flush after every log message,
79 # to an integer to flush every N messages, or to false, nil, or zero to
80 # never auto-flush. If you turn auto-flushing off, be sure to regularly
81 # flush the log yourself -- it will eat up memory until you do.
82 def auto_flushing=(period)
86 when false, nil, 0; MAX_BUFFER_SIZE
88 else raise ArgumentError, "Unrecognized auto_flushing period: #{period.inspect}"
93 @log.write(@buffer.slice!(0..-1).to_s) unless @buffer.empty?
98 @log.close if @log.respond_to?(:close)
104 flush if @buffer.size >= @auto_flushing