Ruby Date范围和匹配

时间:2013-04-17 20:12:07

标签: ruby

我正在为我的工作环境编写一个小的日志嗅探器程序,它在日志中搜索几个关键字,让用户知道他们有一些要查看的内容。这一部分非常简单,但我试图实现的功能之一是用户可以选择今天他们想要走多远的形式,所以他们不会在几个月之前收到不再重要的错误

我已经有了约会,而且从现在开始我和用户指定的范围有差距。我只是不确定如何获得范围和匹配工作。这是我的代码:

require 'date'
### Get the logfile path from the user
p "What is the path to your log file?"
logfile = gets.chomp

### Get number of days user would like to go back
p "How many days back from today would you like to look?"
num_days = gets.chomp


############################################################################################
### Define Log class. Accept argumnet for path of the file. Called by foo = Log.new
############################################################################################
class Log

    def scan_log(file_name, days)
        error_exists = false
        verify = false
        apn = false
        strict = false
        days = days.to_i
        # time = Time.now.strftime("%Y-%m-%d")
        now = Date.today
        days_ago = (now - days)
        p now
        p days_ago

        File.open(file_name, "r") do |file_handle|
            file_handle.each_line do |line|
                if line =~ /Unable to verify signature/
                    verify = true
                    error_exists = true
                end

                if line =~ /gateway.push.apple.com/
                    apn = true
                    error_exists = true
                end

                if line =~ /Data truncation/
                    strict = true
                    error_exists = true
                end
            end
        end

        p "Verify signature error found" if verify


        p "You have an APNS error" if apn


        p "You have strict mode enabled" if strict

    end

end

l = Log.new
l.scan_log(logfile, num_days)

我的想法是file_handle.each_line下的循环可以...我将在循环中包含现有的if语句,并且循环将匹配用户设置的日期范围与日志中的日期。日志中的格式为:

2013-04-17 15:10:42,767

我不关心时间戳,只关心日期戳。

谢谢,如果你能提供帮助。

2 个答案:

答案 0 :(得分:1)

解析自由格式日期的一种有效方法是:

 > Time.parse(" 2013-04-17 13:15:24 -0700 ").strftime("%Y-%m-%d")
  => "2013-04-17" 
 > Time.parse("Wed Apr 17 13:15:09 PDT 2013 ").strftime("%Y-%m-%d")
  => "2013-04-17" 

假设用户以“%Y-%m-%d”格式和时间范围指定start_date,您可以这样做:

 start_date = Time.parse( user_provided_date ) # e.g. "2013-04-10"
 log_date = Time.parse( line )

 do_something if (start_date - log_date) < number_of_seconds  # or whatever time range

如果您只想显示比给定时间范围更新的所有日志,那么您可以这样做:

 log_date = Time.parse( line )

 do_something if (Time.now - log_date) < number_of_seconds  # or whatever time range

要获得Rails风格的漂亮时间范围,例如1.day或12.hours,您可以包含ActiveSupport::Duration

答案 1 :(得分:0)

您可以从日期构建范围(如问题标题所示)并使用它的include?方法。

require 'date'

puts "How many days back from today would you like to look?"
days_back = gets.to_i #input: 3

logline_date = "2013-04-17 15:10:42, 767"

end_date = Date.today
start_date = end_date - days_back
selected_range = start_date..end_date

p selected_range.include?( Date.parse( logline_date )) #true (today for me, that is)