Get Difference between two date field with ruby filter


(Ritesh) #1

Hi All

I have been trying the ruby code to get the difference between 2 dates

Start Date : 2017-06-13T01:17:07.000Z
End Date :  2017-07-13T01:17:10.000Z

I need difference between these 2 dates. I have dried this but i get ruby exception error

  ruby {
      init => "require 'time'"
      code => "
        start = Time.iso8601(event['Start Date'].to_s).to_i;
        end = Time.iso8601(event['End Date'].to_s).to_i;
        event['timediff'] = start - end;
        "
      add_tag => [ "calculated_time_difference" ]
    }

(Christian Saide) #2

Given you have already taken the raw log data that contains the Start Date and End Date and parsed them into fields of the event. I would first pass the two fields into the following:

        date {
            match => [ "Start Date", "ISO8601" ]
            target => "start_date"
        }
        date {
            match => [ "End Date", "ISO8601" ]
            target => "end_date"
        }

Then you can use the ruby filter like so:

  ruby {
      init => "require 'time'"
      code => "
        diff = event.get('start_date') - event.get('end_date')
        event.set('timediff') = diff;
        "
      add_tag => [ "calculated_time_difference" ]
    }

Note the the .get and .set are new in the later versions of logstash and depending on the particular version you are using you may need to use the syntax you originally posted, i.e. event['start_date']

If you haven't parsed them into fields I would look into using grok, to pull the fields out of the raw message. another good resource if you are having trouble creating the grok is grok debugger.


(system) #3

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.