diff --git a/console_libraries/prom.lib b/console_libraries/prom.lib index ca1c9617c..1edf475e1 100644 --- a/console_libraries/prom.lib +++ b/console_libraries/prom.lib @@ -36,6 +36,7 @@ var PATH_PREFIX = "{{ pathPrefix }}"; {{ define "humanizeNoSmallPrefix" }}{{ if and (lt . 1.0) (gt . -1.0) }}{{ printf "%.3g" . }}{{ else }}{{ humanize . }}{{ end }}{{ end }} {{ define "humanize1024" }}{{ humanize1024 . }}{{ end }} {{ define "humanizeDuration" }}{{ humanizeDuration . }}{{ end }} +{{ define "humanizePercentage" }}{{ humanizePercentage . }}{{ end }} {{ define "humanizeTimestamp" }}{{ humanizeTimestamp . }}{{ end }} {{ define "printf.1f" }}{{ printf "%.1f" . }}{{ end }} {{ define "printf.3g" }}{{ printf "%.3g" . }}{{ end }} diff --git a/docs/configuration/template_reference.md b/docs/configuration/template_reference.md index 8791d68b3..fe2b60b23 100644 --- a/docs/configuration/template_reference.md +++ b/docs/configuration/template_reference.md @@ -56,6 +56,7 @@ If functions are used in a pipeline, the pipeline value is passed as the last ar | humanize | number | string | Converts a number to a more readable format, using [metric prefixes](https://en.wikipedia.org/wiki/Metric_prefix). | humanize1024 | number | string | Like `humanize`, but uses 1024 as the base rather than 1000. | | humanizeDuration | number | string | Converts a duration in seconds to a more readable format. | +| humanizePercentage | number | string | Converts a ratio value to a fraction of 100. | | humanizeTimestamp | number | string | Converts a Unix timestamp in seconds to a more readable format. | Humanizing functions are intended to produce reasonable output for consumption diff --git a/template/template.go b/template/template.go index de6ee5453..0eb0ed2be 100644 --- a/template/template.go +++ b/template/template.go @@ -243,6 +243,9 @@ func NewTemplateExpander( } return fmt.Sprintf("%.4g%ss", v, prefix) }, + "humanizePercentage": func(v float64) string { + return fmt.Sprintf("%.4g%%", v*100) + }, "humanizeTimestamp": func(v float64) string { if math.IsNaN(v) || math.IsInf(v, 0) { return fmt.Sprintf("%.4g", v) diff --git a/template/template_test.go b/template/template_test.go index caf816151..60b65c14f 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -197,6 +197,11 @@ func TestTemplateExpansion(t *testing.T) { input: []float64{math.Inf(1), math.Inf(-1), math.NaN()}, output: "+Inf:+Inf:+Inf:+Inf:-Inf:-Inf:-Inf:-Inf:NaN:NaN:NaN:NaN:", }, + { + // HumanizePercentage - model.SampleValue input. + text: "{{ -0.22222 | humanizePercentage }}:{{ 0.0 | humanizePercentage }}:{{ 0.1234567 | humanizePercentage }}:{{ 1.23456 | humanizePercentage }}", + output: "-22.22%:0%:12.35%:123.5%", + }, { // HumanizeTimestamp - model.SampleValue input. text: "{{ 1435065584.128 | humanizeTimestamp }}",