Skip to content

Commit

Permalink
Add exclude and include to filter by regex
Browse files Browse the repository at this point in the history
  • Loading branch information
raags committed Dec 29, 2020
1 parent ed330c6 commit bff0c7d
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -117,6 +118,43 @@ func CreateInfluxMetrics(samples model.Vector, metricPrefix string) string {
return metrics
}

func FilterSamples(samples model.Vector, includeRegex string, excludeRegex string) (model.Vector, error) {
var reInclude, reExclude *regexp.Regexp
var err error

if includeRegex != "" {
reInclude, err = regexp.Compile(includeRegex)
if err != nil {
return nil, err
}
}

if excludeRegex != "" {
reExclude, err = regexp.Compile(excludeRegex)
if err != nil {
return nil, err
}
}

var filteredSamples model.Vector
for _, sample := range samples {
metric_name := string(sample.Metric["__name__"])

var matchInclude, matchExclude bool
if reInclude != nil {
matchInclude = reInclude.MatchString(metric_name)
}
if reExclude != nil {
matchExclude = reExclude.MatchString(metric_name)
}

if matchInclude == true && matchExclude == false {
filteredSamples = append(filteredSamples, sample)
}
}
return filteredSamples, nil
}

func OutputMetrics(samples model.Vector, outputFormat string, metricPrefix string) error {
output := ""

Expand Down Expand Up @@ -239,6 +277,8 @@ func main() {
promURL := flag.String("prom-url", "http://localhost:9090", "Prometheus API URL.")
queryString := flag.String("prom-query", "up", "Prometheus API query string.")
outputFormat := flag.String("output-format", "influx", "The check output format to use for metrics {influx|graphite|json}.")
includeRegex := flag.String("include-regex", "", "Regex on metric names to include (applied first before -exclude-regex)")
excludeRegex := flag.String("exclude-regex", "", "Regex on metric names exclude (applied after -include-regex)")
metricPrefix := flag.String("metric-prefix", "", "Metric name prefix, only supported by line protocol output formats.")
insecureSkipVerify := flag.Bool("insecure-skip-verify", false, "Skip TLS peer verification.")
flag.Parse()
Expand Down Expand Up @@ -270,6 +310,14 @@ func main() {
}
}

if *includeRegex != "" || *excludeRegex != "" {
samples, err = FilterSamples(samples, *includeRegex, *excludeRegex)
if err != nil {
log.Fatal(err)
os.Exit(2)
}
}

err = OutputMetrics(samples, *outputFormat, *metricPrefix)

if err != nil {
Expand Down

0 comments on commit bff0c7d

Please sign in to comment.