Splunk Search

How to search for the last 5 events of type X that happened prior to an event of type Y?

emamedov
Explorer

I am trying to find the last 5 events of a type x that happened before an event of type y. An example would be:

Event x : User login
Event y : Product added to cart

Log:

Apr 25 15:10:30 |DEBUG| [TestCaseImpl:50] User login: User1
Apr 25 15:12:51 |DEBUG| [TestCaseImpl:50] User login: User2
Apr 25 15:13:11 |DEBUG| [TestCaseImpl:50] User login: User3
Apr 25 15:14:00 |DEBUG| [TestCaseImpl:50] User login: User4
Apr 25 15:17:23 |DEBUG| [TestCaseImpl:50] User login: User5
Apr 25 15:17:23 |DEBUG| [TestCaseImpl:332] Product added to cart: ProductXYZ

I would want the result to return the events for [User1,User2,User3,User4,User5].

0 Karma

Richfez
SplunkTrust
SplunkTrust

Another option is streamstats. If those are in order, then you could do something like the following.

First, filter your search to just those lines up front. Then streamstats with a window of 6 and set a flag on the lines you want to keep. Lastly we create a transaction to group them together. In the middle I'm going a rex to pull out the product so that I can use it later.

sourcetype=MySourceType "User login" OR "Product added to cart"
| rex "Product added to cart:\s+(?<ProductAdded>.*)$"
| streamstats window=6 first(ProductAdded) as TriggerGroup
| transaction maxevents=6 endswith="Product added to cart" TriggerGroup

This will take some tweaking, I am sure, and I only guessed at the rex (and probably have a typo in it anyway).

For more information and another example, see this Answers post on including 100 previous lines before an event in an alert.

0 Karma

somesoni2
SplunkTrust
SplunkTrust

Wild guess

index=foo sourcetype=bar "User login" OR "Product added to cart" | transaction startswith="User login" endswith="Product added to cart" maxevents=6 
0 Karma
Get Updates on the Splunk Community!

Index This | I am a number, but when you add ‘G’ to me, I go away. What number am I?

March 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...

What’s New in Splunk App for PCI Compliance 5.3.1?

The Splunk App for PCI Compliance allows customers to extend the power of their existing Splunk solution with ...

Extending Observability Content to Splunk Cloud

Register to join us !   In this Extending Observability Content to Splunk Cloud Tech Talk, you'll see how to ...