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
Revered Legend

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!

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...

Introducing the 2024 Splunk MVPs!

We are excited to announce the 2024 cohort of the Splunk MVP program. Splunk MVPs are passionate members of ...

Splunk Custom Visualizations App End of Life

The Splunk Custom Visualizations apps End of Life for SimpleXML will reach end of support on Dec 21, 2024, ...