Class: Base::LogParser

Inherits:
Object
  • Object
show all
Defined in:
lib/base/log_parser.rb

Overview

Parse a log file

Constant Summary collapse

LOG_LINES =
{}

Instance Method Summary collapse

Constructor Details

#initialize(file, options = {}) ⇒ LogParser

LogParser initializer file The fileobject this LogParser wil operate on.



9
10
11
12
13
14
15
# File 'lib/base/log_parser.rb', line 9

def initialize(file, options = {})
  @file_name = file
  @options = options
  @file_size = File.size(@file_name)
  
  self.initialize_hook(options) if self.respond_to?(:initialize_hook)
end

Instance Method Details

#each(*line_types, &block) ⇒ Object

Finds a log line and then parses the information in the line. Yields a hash containing the information found. *line_types The log line types to look for (defaults to LOG_LINES.keys). Yeilds a Hash when it encounters a chunk of information.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/base/log_parser.rb', line 31

def each(*line_types, &block)
  log_lines_hash = self.class::LOG_LINES

  
  # parse everything by default 
  line_types = log_lines_hash.keys if line_types.empty?

  File.open(@file_name) do |file|
  
    file.each_line do |line|
    
      #@progress_handler.call(file.pos, @file_size) if @progress_handler
      
      line_types.each do |line_type|
        if log_lines_hash[line_type][:teaser] =~ line
          if log_lines_hash[line_type][:regexp] =~ line
            request = { :type => line_type, :line => file.lineno }
            log_lines_hash[line_type][:params].each do |key, value|
              request[key] = case value
                when Numeric; $~[value]
                when Array;   $~[value.first].send(value.last)
                else; nil
              end
            
            end
            
            yield(request) if block_given?
          else
            warn("Unparsable #{line_type} line: " + line[0..79]) unless line_type == :failed
          end
        end            
      end
    end
    @progress_handler.call(:finished, @file_size) if @progress_handler
  end      
end

#progress(&block) ⇒ Object



17
18
19
# File 'lib/base/log_parser.rb', line 17

def progress(&block)
  @progress_handler = block
end

#warn(message) ⇒ Object

Output a warning message The warning message (object)



23
24
25
# File 'lib/base/log_parser.rb', line 23

def warn(message)
  puts " -> " + message.to_s
end