Search code examples
grafanagrafana-lokilogql

Count number of unique values using Loki LogQL


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)


Solution

  • 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