Search code examples
bosun

How do I format numbers within Bosun templates?


In a Bosun template, is it possible to format the output of an evaluated variable from the alert to less decimal places of precision?

Simple Example:

template test_template{
    subject = test
    body = {{.Eval .Alert.Vars.average_runtime}} seconds
}
alert test_alert{
    template test_template
    $average_runtime = avg(q("avg:metric_name", "24h",""))
    crit = $average_runtime > 150.0
}

Results in

190.71165892385326 seconds

in the template body, which is unnecessarily precise. Ideally I would like to see:

190.71 seconds


Solution

  • In go templates you can use printf to format output according to whatever format string you want. This snippet works for me:

    template test_template{
      subject = test
      body = {{printf "%.3f" (.Eval .Alert.Vars.average_runtime)}} seconds
    }
    
    alert test_alert{
      template = test_template
      $average_runtime = 1234.5678999
      crit = 1
    }