干掉触发器操作员

时间:2014-08-08 23:00:20

标签: ruby optimization dry

目前试图让我的触发器操作员干涸,我不确定最好的方法。想法?

@log_file = "07-07-14 to 07-13-14_debug.log"

def error_sort
  File.readlines(@log_file).each do |line|
    if (line =~ /<DEBUG>/ .. line =~ /<(?!DEBUG).+>/) && line !~ /<(?!DEBUG).+>/
      File.open("debug.txt", "a") << line
    elsif (line =~ /<INFO >/ .. line =~ /<(?!INFO ).+>/) && line !~ /<(?!INFO ).+>/
      File.open("info.txt", "a") << line
    elsif (line =~ /<WARN >/ .. line =~ /<(?!WARN ).+>/) && line !~ /<(?!WARN ).+>/
      File.open("warn.txt", "a") << line
    elsif (line =~ /<ERROR>/ .. line =~ /<(?!ERROR).+>/) && line !~ /<(?!ERROR).+>/
      File.open("error.txt", "a") << line
    elsif (line =~ /<FATAL>/ .. line =~ /<(?!FATAL).+>/) && line !~ /<(?!FATAL).+>/
      File.open("fatal.txt", "a") << line
    else
      nil
    end
  end
end

1 个答案:

答案 0 :(得分:0)

我会从这样的事情开始:

LOGLEVELS = ['debug', 'info', 'warn', 'error', 'fatal']

def loglevel?(level, line)
  level = level.upcase
  (line =~ /<#{level}>/ .. line =~ /<(?!#{level}).+>/) && line !~ /<(?!#{level}).+>/
end

def error_sort
  File.readlines(@log_file).each do |line|
    LOGLEVES.each do |level| 
      File.open("#{level}.txt", "a") << line if loglevel?(level, line)
    end
  end
end