Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Last active December 14, 2015 04:18
Show Gist options
  • Save tkfm-yamaguchi/5026728 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/5026728 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# coding: utf-8
require 'date'
module DateTimeStringer
def to_sdate
strftime("%Y-%m-%d")
end
def to_stime
strftime("%H:%M:%S")
end
end
class Date
include DateTimeStringer
end
class DateTime
include DateTimeStringer
end
class ApacheLog
attr_accessor :line, :time
class << self
def extract_time(line)
DateTime.parse(line.scan(/\[([^\]]+)\]/).flatten.first.gsub!(/\//,'-').gsub!(/^([^:]+):/,'\1 '))
end
end
def initialize(line)
@line = line
@time = ApacheLog.extract_time(@line)
end
def to_line
time_s = @time.strftime("%d/%b/%Y:%H:%M:%S %z")
@line.sub(/\[[^\]]+\]/, "[#{time_s}]")
end
end
class LogFile
attr_accessor :filename, :time, :head, :tail
def initialize(filename)
@filename = filename
get_head!
get_tail!
get_date_from_filename!
end
def get_date_from_filename!
@time = Date.parse(@filename.split(".").last.scan(/(\d{4})(\d{2})(\d{2})/).flatten.join("-"))
end
def method_missing(name, *args)
case name.to_s
when /^get_(head|tail)\!$/
return instance_variable_set(:"@#{$1}", ApacheLog.new(`#{$1} -1 #{@filename}`))
end
super(name, *args)
end
end
class Kompairer
attr_accessor :messages
class << self
def validate(logs)
self.new(logs)
end
end
def initialize(logs)
@logs = logs
@messages = []
validate!
end
def validate!
kompair = proc{|a, b| a.time.to_sdate == b.time.to_sdate }
unless kompair[@logs, @logs.head]
@messages << "File name date and date of head are unmatched"
end
unless kompair[@logs, @logs.tail]
@messages << "File name date and date of tail are unmatched"
end
unless kompair[@logs.head, @logs.tail]
@messages << "Dates of head and tail are unmatched"
end
end
def ok?
@messages.empty?
end
end
if __FILE__ == $0
fname = ARGV[0]
logs = LogFile.new(fname)
kompaired = Kompairer.validate(logs)
unless kompaired.ok?
puts "[ERROR] #{fname}\n#{@messages.join("\n")}"
else
puts "[OK] #{fname} (s: #{logs.head.time.to_stime}, e: #{logs.tail.time.to_stime})"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment