The Query inspector in Grafana can be helpful when you’re trying to figure out why your query is failing, or why it’s taking too long to return a result. While Grafana displays some basic information about your query by default, in this post you’ll learn how to add your own stats for you query.
Note: For simpler data sources that fetch data through a single HTTP request and returns it more or less unprocessed, you probably don’t need to worry about custom stats.
If a data source query fans out to several APIs requests, you might want to see how long each individual request took. Or, if you’re processing the data before it gets displayed, the user may want to compare how long it took to transfer the data over the network with the time spent processing it. Both these cases are examples of when you might want to add custom stats to your data source.
You’re already using the data.Frame
type to pass the query results back to the user. In addition to the fields containing the data, data.Frame
also has a Meta
field that allows you to pass metadata about the data frame back to the browser. While data.FrameMeta
supports several other types of metadata, in this post we’ll focus on the Stats
field.
To add your own stats to your queries, add the metadata to your data frame with a collection of query stats:
frame.Meta = &data.FrameMeta{
Stats: []data.QueryStat{numParsedTokens},
}
numParsedToken
is an object of type data.QueryStat
with a value and a field config:
numParsedTokens := data.QueryStat{
FieldConfig: data.FieldConfig{
DisplayName: "Parsed tokens",
},
Value: 100,
}
- The value is the measurement you want to report, for example processing time in milliseconds, or the number of queries.
- The field config lets you configure how the value should appear to the user. The only required field is the display name, which is the name of your metric.
Your custom stats appear in the query inspector, under Data source stats.
To display the unit of measurement next to your metric, set the Unit
field in the query stat.
processingTime := data.QueryStat{
FieldConfig: data.FieldConfig{
DisplayName: "Total processing time",
Unit: "ms",
},
Value: 85,
}
By adding custom stats for your data source queries, you can help your users to figure out how they can improve their queries, and use your data source more efficiently.