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
Did you miss .conf21 Virtual?

Good news! The event's keynotes and many of its breakout sessions are now available online, and still totally FREE!