How-To: Use Conditional Expressions

Conditional expressions can be used to augment and expand the processing of data within your repository so that it is easier to process or report on information without having to modify or alter the parsing of the source data.

For example, when processing Apache server logs, using a conditional expression enables you to differentiate between local and remote clients by translating the contents of an event into a simpler form that can then be used as a metric. In the example below, a new field, local is created depending on whether the client IP address is determined as local or not using the case expression:

logscale
case { client = "::1"
| local := "true";
       client = "127.0.0.1"
| local := "true";
   *
| local := "false"}
| groupBy(field=local, function = sum(responsesize))

This can be broken down as follows:

logscale
case { client = "::1"
| local := "true";

We open the case expression with the first comparison; if the client field equals ::1, the IPv6 address for the localhost, set the field local to true.

logscale
client = "127.0.0.1"
| local := "true";

We add a second clause, this time for the IPv4 localhost address.

logscale
*
| local := "false"}

Finally, we have to add a catchall, or else clause that sets local to false for any other IP address.

logscale
| groupBy(field=local, function = sum(responsesize))

Then we use a groupBy to collate this information and provide a sum of the data size returned, effectively giving the amount of data returned to localhost or another on the network.

Because the selection is conditional it can be used for to determine multiple expressions to set a field value based on different input criteria. For example, to identify local or oversize responses:

logscale
case { responsesize > 100000
| packetype := "oversize";
       client = "::1"
| packetype := "local";
       *
| packetype := "remote"}
| groupBy(field=packetype, function = sum(responsesize))

In this example we are determining the total size returned whether the data is local or remote, of if it's oversized regardless of destination.

Additional Guidance

Some guidance for using conditionals:

  • Matching expressions should be terminated by a semicolon

  • It can be useful to use the else clause within a case expressions as catchall expression to capture the remaining events that don't match earlier expressions. If not used, these events will be filtered from the output.