Filtering Metrics
Report Filtering
App Metrics allows you to filter Metrics per reporter.
Below is an example reporting configuration which provides a filter to a console reporter filtering Metrics containing a tag key of "filter-tag1" and are Counters
private static void ConfigureMetrics(IServiceCollection services)
{
services
.AddMetrics(options =>
{
options.ReportingEnabled = true;
options.GlobalTags.Add("env", "uat");
})
.AddReporting(factory =>
{
var filter = new DefaultMetricsFilter()
.WhereType(MetricType.Counter)
.WhereMetricTaggedWithKey("filter-tag1", "filter-tag2")
.WithHealthChecks(true)
.WithEnvironmentInfo(true);
factory.AddConsole(new ConsoleReporterSettings
{
ReportInterval = TimeSpan.FromSeconds(10),
}, filter);
});
}
Globally Filtering
Metrics can also be set at a global level which would apply to all Metric data queries.
Below is an example of how to apply a global filter in a Web Host.
public void ConfigureServices(IServiceCollection services)
{
services
.AddLogging()
.AddRouting(options => { options.LowercaseUrls = true; });
services.AddMvc();
var filter = new DefaultMetricsFilter().WhereType(MetricType.Counter);
services
.AddMetrics()
.AddGlobalFilter(filter)
.AddJsonSerialization()
.AddHealthChecks()
.AddMetricsMiddleware();
}
Requesting the /metrics
endpoint with the above configuration would result in only Counter Metrics being shown in the response.
Overriding the Global Filter
In cases where a global filter is set as well as a filter on a reporter, the reporter's filter will be used instead.
It is also possible to override the global filter if you where to retrieve a snapshot of the current metrics data via the Advanced Metric contract.
public class MyService
{
private readonly IMetrics _metrics;
public MyService(IMetrics metrics)
{
_metrics = metrics;
}
public MetricsDataValueSource DoSomething()
{
var filter = new DefaultMetricsFilter().WhereMetricNameStartsWith("test_");
return _metrics.Snapshot.Get(filter);
}
}
Supported Filtering
Metrics can be filtered by:
- Metric Type
- Tags
- Context
- Metric Name (Exact match or where name starts with)
Tip
Custom Metric Filters can be implemented rather than using the DefaultMetricsFilter by implementing IMetricsFilter.