Count number of unique values using Loki LogQL
Asked Answered
L

1

8

I have a log stream that has a UserID= label. I'm trying to count the number of unique users within an hour.

Here's an example of my log stream:

ts=2022-09-16T10:52:54.21344541Z level=INFO UserID=65166 elapsed=2.364015ms
ts=2022-09-16T10:52:51.580617785Z level=INFO UserID=24413 elapsed=2.324235ms
ts=2022-09-16T10:52:48.947248244Z level=INFO UserID=65166 elapsed=2.818146ms
ts=2022-09-16T10:52:41.51854716Z level=INFO UserID=24413 elapsed=2.633352ms
ts=2022-09-16T10:51:14.584272582Z level=INFO UserID=24413 elapsed=2.04884ms
ts=2022-09-16T10:51:14.45564065Z level=INFO UserID=65166 elapsed=4.889566ms

The closest thing I've managed to achieve is count the number of requests for each user, but I just need to know the number of unique users in a given time range. Here's what I have:

count(count_over_time({app="app"} | logfmt [1h])) by (UserID)

Least answered 17/9, 2022 at 10:46 Comment(1)
Fun fact: LogsQL query for counting the number of unique userIDs over the last hour is much simpler: _time:1h | count_uniq(UserID)Hedveh
L
14

After playing around a bit more, I realized I could just wrap the above query in another count() and get the number of unique users that way. For completeness sake, here's the query:

count(count(count_over_time({app="app"} | logfmt [1h])) by (UserID))

And this is what I get:

enter image description here

Least answered 17/9, 2022 at 12:51 Comment(2)
how to provide a name to the result?Sellars
if you mean on grafana, you can set a custom legend under options below the query editor. just select legend and change from Auto to Custom and set whatever you wantLeast

© 2022 - 2024 — McMap. All rights reserved.