Class: Logbert::Handlers::TimeRotator

Inherits:
BaseHandler show all
Defined in:
lib/logbert/handlers/time_rotator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseHandler

#formatter, #formatter=, #publish

Constructor Details

#initialize(path, options = {}) ⇒ TimeRotator

Returns a new instance of TimeRotator.



29
30
31
32
33
34
35
# File 'lib/logbert/handlers/time_rotator.rb', line 29

def initialize(path, options = {})
  @path                = path
  @timestamp_formatter = options[:timestamp_formatter] || LocaltimeFormatter.new
  @interval            = options.fetch(:iterval, 24 * 60 * 60)
  
  rotate_log!
end

Instance Attribute Details

#expiration_timeObject (readonly)

Returns the value of attribute expiration_time.



27
28
29
# File 'lib/logbert/handlers/time_rotator.rb', line 27

def expiration_time
  @expiration_time
end

#intervalObject (readonly)

Returns the value of attribute interval.



27
28
29
# File 'lib/logbert/handlers/time_rotator.rb', line 27

def interval
  @interval
end

#pathObject (readonly)

Returns the value of attribute path.



26
27
28
# File 'lib/logbert/handlers/time_rotator.rb', line 26

def path
  @path
end

#streamObject (readonly)

Returns the value of attribute stream.



26
27
28
# File 'lib/logbert/handlers/time_rotator.rb', line 26

def stream
  @stream
end

#timestamp_formatterObject (readonly)

Returns the value of attribute timestamp_formatter.



26
27
28
# File 'lib/logbert/handlers/time_rotator.rb', line 26

def timestamp_formatter
  @timestamp_formatter
end

Instance Method Details

#emit(output) ⇒ Object



59
60
61
62
63
# File 'lib/logbert/handlers/time_rotator.rb', line 59

def emit(output)
  rotate_log! if rotation_needed?
  @stream.puts output
  @stream.flush
end

#rotate_log!Object



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/logbert/handlers/time_rotator.rb', line 43

def rotate_log!
  if @stream and not @stream.closed?
    @stream.close
  end
  
  if File.exists? @path
    FileUtils.mv @path, archive_destination
  end
  
  @stream = File.open(@path, "ab")

  @expiration_time = Time.now + @interval
end

#rotation_needed?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/logbert/handlers/time_rotator.rb', line 38

def rotation_needed?
  Time.now > @expiration_time
end