In this tutorial, I will show you how to perform arithmetic operations (sum, substract, multiple, divide two or more fields) in Logstash.
We will use the Ruby filter plugin inside the filter
section of the Logstash configuration file so that
In short, an example of adding two fields in Logstash looks like this:
Let's dive deeper into the details.
Contents
- How to Perform Arithmetic Operations in Logstash
- Examples of Using Arithmetic Operations in Logstash
- Conclusion
How to Perform Arithmetic Operations in Logstash
The simplest way to perform arithmetic operations in Logstash is to use the Ruby filter plugin.
I will use the following log as an example for the rest of this tutorial:
How to Add Fields in Logstash
To add (sum) two fields in Logstash, you can use the Ruby filter and the +
operator:
The code above will convert field1
and field2
to integers, then add them together and store the result in a new field called sum
.
So the result log will look like this:
You can learn more about summing two fields in Logstash by reading this in-depth tutorial: How to Sum Two Fields in Logstash.
How to Subtract Fields in Logstash
To subtract two fields in Logstash, you can use the Ruby filter and the -
operator:
Similarly, we get the following result:
How to Multiply Fields in Logstash
To multiply two fields in Logstash, you can use the Ruby filter and the *
operator:
The result log will look like this:
How to Divide Fields in Logstash
To divide two fields in Logstash, you can use the Ruby filter and the /
operator:
In this case, we convert field1
and field2
to floats instead of integers because we want to get the decimal value of the quotient.
The result log will look like this:
Examples of Using Arithmetic Operations in Logstash
There are some common cases I usually use arithmetic operations in Logstash, let's take a look at them.
In this section, I will use the Logstash config from this tutorial to parse JSON string logs into JSON objects.
Calculate Total Seconds from Duration
Let's say you have a field called duration
that stores the duration of an event in the format HH:MM:SS
.
To calculate the total seconds from the duration, you can use the following code:
The resulting log will look like this:
Calculate Sum of Values in an Array Field
Let's say you have a field called values
that stores an array of integers.
To calculate the sum of values in the values
field, you can use the following code:
The resulting log will look like this:
Conclusion
In this tutorial, you have learned how to perform arithmetic operations in Logstash using the Ruby filter plugin.
If you have any questions, please leave a comment below.
Comments
Be the first to comment!