在grafana(使用go模板进行Loki线模板)中,我想划分一个字段(毫秒)并获得一个浮点结果。
这是我想做的:
| logfmt | line_format "{{ .microsec | float64 | div 1000 | printf \"%6.3f\" }}ms"
但是,这显然不起作用,因为 div
是整数除法函数。
以下方法有效(但不能除以数字):
| logfmt | line_format "{{ .microsec | float64 | printf \"%8.0f\" }}μs"
如何获得毫秒格式的输出?
编辑: 还有一个 divf 函数,但文档说“执行整数除法”。我用它得到了非常奇怪的结果(所以我不知道如何使用它):
{{ .microsec | float64 | printf \"%8.0f\" }}μs {{ .microsec | float64 | divf 1000 | printf \"%6.3f\" }}ms?divf
6332μs 0.158ms?divf
22959μs 0.044ms?divf
7034μs 0.142ms?divf
最佳答案
Grafana docs声明:
All sprig functions have been added to the template stage in Loki 2.3(along with function described below).
还有Float Math Functions包含一个 divf
函数来执行浮点除法。
A pipeline may be "chained" by separating a sequence of commands with pipeline characters '|'. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.
所以当你这样做时:
{{ .microsec | float64 | divf 1000 | float64 | printf "%6.3f" }}ms
您实际上是将 1000 除以微秒值。显然你想要相反的结果,所以只需这样做:
{{ divf .microsec 1000 | printf "%6.3f" }}ms
另请注意,在不支持浮点除法的情况下(意味着没有 divf
函数),您仍然可以使用整数算术来完成此操作。
{{ printf "%d.%03d" (div .microsec 1000) (mod .microsec 1000) | float64 }}ms
更多详情,请参阅 How to get a float result from a HELM template division operation?
关于go - Go模板中的浮点除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71998319/