Class: Sherlog::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/sherlog_holmes/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(patterns = {}, filter = nil) ⇒ Parser

Returns a new instance of Parser.



26
27
28
29
30
31
32
33
34
# File 'lib/sherlog_holmes/parser.rb', line 26

def initialize(patterns = {}, filter = nil)
  @filter = filter
  @patterns = {
      exception: /^$/,
      stacktrace: /^$/
  }.merge patterns
  @filter ||= filter { |entry| true }
  @listeners = []
end

Instance Method Details

#collectObject



36
37
38
39
40
41
42
# File 'lib/sherlog_holmes/parser.rb', line 36

def collect
  result = Result::new
  on_new_entry do |entry|
    result << entry
  end
  result
end

#filter(filter = nil, &block) ⇒ Object



49
50
51
52
# File 'lib/sherlog_holmes/parser.rb', line 49

def filter(filter = nil, &block)
  @filter = filter if filter
  @filter = Filter::new &block if block
end

#on_new_entry(listener = nil, &block) ⇒ Object



44
45
46
47
# File 'lib/sherlog_holmes/parser.rb', line 44

def on_new_entry(listener = nil, &block)
  listener ||= block
  @listeners << listener
end

#parse(input) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/sherlog_holmes/parser.rb', line 58

def parse(input)
  entry = nil
  foreach input do |line|
    try_guess_pattern line unless @patterns[:entry]
    if @patterns[:entry] =~ line
      entry_data = Hash[Regexp.last_match.names.map { |k| [k.to_sym, Regexp.last_match[k].to_s.strip] }]
      # notify the last entry parsed
      notify entry if entry and @filter.accept? entry
      entry = Entry::new entry_data
      entry.raw_content = line.chomp
      entry.exceptions << Regexp.last_match[:exception] if @patterns[:exception] =~ entry.message
    else
      if entry
        if entry.exception? and @patterns[:stacktrace] =~ line
          entry.stacktrace << line.chomp
        else
          entry << line.chomp
        end
        entry.exceptions << Regexp.last_match[:exception] if @patterns[:exception] =~ line
        entry.raw_content << $/ << line.chomp
      end
    end
  end
  # notify the last entry parsed
  notify entry if entry and @filter.accept? entry
end

#patterns(config) ⇒ Object



54
55
56
# File 'lib/sherlog_holmes/parser.rb', line 54

def patterns(config)
  @patterns.merge! config
end