Ruby Filter Syntax

I'm trying to take a pair of fields that contain a date and subtract one from the other. However, my code is wrong somewhere and i get an error. This error occurs three times for each event, so I assume it's a syntax error in all three ruby filters I use in this pipeline.

[ERROR][logstash.filters.ruby    ] Ruby exception occurred: undefined method `[]' for #<LogStash::Event:0x5e20cf07>`

Here's what i have in the pipeline.

    ##convert old.sys_updated date/time data type to epoch
    ruby { code => "event['old.sys_updated_epoch'] = event['old.sys_updated_time'].to_i" }
    #Convert current timestamp to epoch
    ruby { code => "event['currenttime_epoch'] = event['sys_updated_on'].to_i" }
    #Calculate difference between old.sys_updated_epoch and currenttime_epoch
    ruby { code => "event['duration_epoch'] = event['currenttime_epoch'] - event['old.sys_updated_epoch']" }

Where is my code wrong at?

Unless you are using a very old version you should be using the event API, so

    ruby { code => "event.set('old.sys_updated_epoch') = event.get('old.sys_updated_time').to_i" }

In addition to the documented get and set methods, event has to_hash and a sprintf method that can be used to resolve sprintf references.

Guess I should have mentioned that I am running Logstash 7.2.0. Unfortunately, that syntax threw an error.

[ERROR][org.logstash.Logstash    ] java.lang.IllegalStateException: Logstash stopped processing because of an error: (SyntaxError) (ruby filter code):2: syntax error, unexpected '='
 event.set('currenttime_epoch') = event.get('sys_updated_on').to_i 

When I change it to using square brackets, the following error is thrown for all three instances of the ruby filter I use.

ruby { code => "event.set['old.sys_updated_epoch'] = event.get['old.sys_updated_time'].to_i" }
[ERROR][logstash.filters.ruby    ] Ruby exception occurred: wrong number of arguments calling `set` (given 0, expected 2)

Giving another read of this documentation, I used the example at the very bottom to correct the syntax and get a functional line of code. Here's the working value.

ruby { code => 'event.set("old.sys_updated_epoch", event.get("old.sys_updated_time").to_i)' }

Sorry about that, I was so focused on changing the square brackets to API calls that I missed the other change required.

1 Like

No worries, incorrect syntax is an easy miss, I do it CONSTANTLY.

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