Methods in Logstash Ruby

I'm trying to get methods working in Logstash Ruby and I'm starting with a very simple one

def output_something(value)
    puts value
end

Then I call the method and try to create a field with a value from it

event.set('[new_field]', output_something('test_text'))

It creates the new field but the value for it is nil

"new_field" => nil,

1 Like

This is expected since your function returns nil. puts prints a string to stdout, it doesn't cause the string to be returned from the function.

It seems I'm also not putting the method in the right place, and I can't find an example in the documentation.

My current code looks like this

ruby {
            code => "
            def testcasebuilder()
                for i in 0..5
                    event.set('new_field', event.get('new_field') + ['test'])
                end
            end
            begin
                event.set('new_field', ['test'])
                testcasebuilder()
            end"
}

I've also tried this

ruby {
            code => "
            begin
                def testcasebuilder()
                    for i in 0..5
                        event.set('new_field', event.get('new_field') + ['test'])
                    end
                end
                event.set('new_field', ['test'])
                testcasebuilder()
            end"
}

Neither of these work. Where should I put my method so that I can call it?

Your code looks okay to me but is there any particular reason you need to use a function instead of just inlining the code?

I'm trying to walk through a nested object to get all the fields with a certain name added to a single field, then I will split that field.

My idea was to create a recursive method to walk through the object.

Have you found a way to do this recursively ? I am in a similar situation where the path to a nested object may vary across multiple events.

Your code looks okay to me but is there any particular reason you need to use a function instead of just inlining the code?

I (too) want to use a function to keep the structure of my code clean.

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