Class: CSGOLytics::LogReader

Inherits:
Object
  • Object
show all
Defined in:
lib/csgolytics/log_reader.rb

Constant Summary collapse

POLL_INTERVAL =
1

Instance Method Summary collapse

Constructor Details

#initialize(logdir) ⇒ LogReader

Returns a new instance of LogReader.



13
14
15
16
# File 'lib/csgolytics/log_reader.rb', line 13

def initialize(logdir)
  @logdir = logdir
  @callbacks = []
end

Instance Method Details

#on_logline(&cb) ⇒ Object



18
19
20
# File 'lib/csgolytics/log_reader.rb', line 18

def on_logline(&cb)
  @callbacks << cb
end

#startObject



22
23
24
25
26
27
28
29
30
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
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/csgolytics/log_reader.rb', line 22

def start
  # tail the logfiles
  loop do
    begin
      # list all logfiles
      @logfiles = {}
      @logfiles_completed = {}
      Dir.entries(@logdir).each do |f|
        if f.end_with?(".log")
          @logfiles[f] = true
        end

        if f =~ /^\.(.*\.log)\.csgolytics_complete$/
          @logfiles_completed[$1] = true
        end
      end

      @logfiles = (@logfiles.keys - @logfiles_completed.keys).sort

      # read each logfile from the last offset and upload new lines
      @logfiles.each_with_index do |fname, logfile_index|
        fpath = File.join(@logdir, fname)
        offset_file_path = File.join(@logdir, ".#{fname}.csgolytics_offset")
        offset = 0
        if File.exists?(offset_file_path)
          offset = IO.read(offset_file_path).to_i
        end

        puts "Reading #{fpath} from #{offset}"

        f = File.open(fpath)
        f.seek(offset)
        while l = (f.readline rescue nil)
          l.encode!('UTF-8', 'UTF-8', :invalid => :replace)
          l.chomp!

          @callbacks.each do |cb|
            cb[l]
          end

          File.write(offset_file_path + "~", f.tell)
          FileUtils.mv(offset_file_path + "~", offset_file_path)
        end

        if logfile_index < @logfiles.length - 1
          FileUtils.touch(File.join(@logdir, ".#{fname}.csgolytics_complete"))
        end
      end
    rescue Exception => e
      $stderr.puts "ERROR: #{e.to_s}"
      $stderr.puts e.backtrace
    end

    sleep POLL_INTERVAL
  end
end