Class: File::Tail::Logfile

Inherits:
File
  • Object
show all
Includes:
File::Tail
Defined in:
lib/file/tail.rb

Overview

This is an easy to use Logfile class that includes the File::Tail module.

Usage

The unix command “tail -10f filename” can be emulated like that:

File::Tail::Logfile.open(filename, :backward => 10) do |log|
  log.tail { |line| puts line }
end

Or a bit shorter:

File::Tail::Logfile.tail(filename, :backward => 10) do |line|
  puts line
end

To skip the first 10 lines of the file do that:

File::Tail::Logfile.open(filename, :forward => 10) do |log|
  log.tail { |line| puts line }
end

The unix command “head -10 filename” can be emulated like that:

File::Tail::Logfile.open(filename, :return_if_eof => true) do |log|
  log.tail(10) { |line| puts line }
end

Instance Attribute Summary

Attributes included from File::Tail

#break_if_eof, #interval, #max_interval, #reopen_deleted, #reopen_suspicious, #return_if_eof, #suspicious_interval

Class Method Summary collapse

Methods included from File::Tail

#backward, #forward, #tail, #wind

Methods inherited from File

#rewind

Class Method Details

.open(filename, opts = {}) ⇒ Object

This method creates an File::Tail::Logfile object and yields to it if a block is given, otherwise it just returns it. The opts hash takes an option like

  • :backward => 10 to go backwards

  • :forward => 10 to go forwards

in the logfile for 10 lines at the start. The buffersize for going backwards can be set with the

  • :bufsiz => 8192 option.

Every attribute of File::Tail can be set with a :attributename => value option.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/file/tail.rb', line 97

def self.open(filename, opts = {}) # :yields: file
  file = new filename
  opts.each do |o, v|
    writer = o.to_s + "=" 
    file.__send__(writer, v) if file.respond_to? writer
  end
  if opts.key?(:wind) or opts.key?(:rewind)
    warn ":wind and :rewind options are deprecated, "\
      "use :forward and :backward instead!"
  end
  if backward = opts[:backward] || opts[:rewind]
    (args = []) << backward
    args << opt[:bufsiz] if opts[:bufsiz]
    file.backward(*args)
  elsif forward = opts[:forward] || opts[:wind]
    file.forward(forward)
  end
  if block_given?
    yield file
    nil
  else
    file
  end
end

.tail(filename, opts = {}) ⇒ Object

Like open, but yields to every new line encountered in the logfile.



123
124
125
126
127
128
129
130
# File 'lib/file/tail.rb', line 123

def self.tail(filename, opts = {})
  if ([ :forward, :backward ] & opts.keys).empty?
    opts[:backward] = 0
  end
  open(filename, opts) do |log|
    log.tail { |line| yield line }
  end
end