github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/docs/sources/logql/template_functions.md (about)

     1  ---
     2  title: Template functions
     3  weight: 30
     4  ---
     5  
     6  # Template functions
     7  
     8  The [text template](https://golang.org/pkg/text/template) format used in `| line_format` and `| label_format` support the usage of functions.
     9  
    10  All labels are added as variables in the template engine. They can be referenced using they label name prefixed by a `.`(e.g `.label_name`). For example the following template will output the value of the path label:
    11  
    12  ```template
    13  {{ .path }}
    14  ```
    15  
    16  Additionally you can also access the log line using the [`__line__`](#__line__) function.
    17  
    18  You can take advantage of [pipeline](https://golang.org/pkg/text/template/#hdr-Pipelines) to join together multiple functions.
    19  In a chained pipeline, the result of each command is passed as the last argument of the following command.
    20  
    21  Example:
    22  
    23  ```template
    24  {{ .path | replace " " "_" | trunc 5 | upper }}
    25  ```
    26  
    27  ## __line__
    28  
    29  This function returns the current log line.
    30  
    31  Signature:
    32  
    33  `line() string`
    34  
    35  Examples:
    36  
    37  ```template
    38  "{{ __line__ | lower }}"
    39  `{{ __line__ }}`
    40  ```
    41  
    42  ## __timestamp__
    43  
    44  This function returns the current log lines timestamp.
    45  
    46  Signature:
    47  
    48  `timestamp() time.Time`
    49  
    50  ```template
    51  "{{ __timestamp__ }}"
    52  `{{ __timestamp__ | date "2006-01-02T15:04:05.00Z-07:00" }}`
    53  `{{ __timestamp__ | unixEpoch }}`
    54  
    55  See the blog: [Parsing and formatting date/time in Go](https://www.pauladamsmith.com/blog/2011/05/go_time.html) for more information.
    56  
    57  ## ToLower and ToUpper
    58  
    59  This function converts the entire string to lowercase or uppercase.
    60  
    61  Signatures:
    62  
    63  - `ToLower(string) string`
    64  - `ToUpper(string) string`
    65  
    66  Examples:
    67  
    68  ```template
    69  "{{.request_method | ToLower}}"
    70  "{{.request_method | ToUpper}}"
    71  `{{ToUpper "This is a string" | ToLower}}`
    72  ```
    73  
    74  > **Note:** In Grafana Loki 2.1 you can also use respectively [`lower`](#lower) and [`upper`](#upper) shortcut, e.g `{{.request_method | lower }}`.
    75  
    76  ## Replace string
    77  
    78  > **Note:** In Loki 2.1 [`replace`](#replace) (as opposed to `Replace`) is available with a different signature but easier to chain within pipeline.
    79  
    80  Use this function to perform a simple string replacement.
    81  
    82  Signature:
    83  
    84  `Replace(s, old, new string, n int) string`
    85  
    86  It takes four arguments:
    87  
    88  - `s` source string
    89  - `old` string to replace
    90  - `new` string to replace with
    91  - `n` the maximun amount of replacement (-1 for all)
    92  
    93  Example:
    94  
    95  ```template
    96  `{{ Replace "This is a string" " " "-" -1 }}`
    97  ```
    98  
    99  The results in `This-is-a-string`.
   100  
   101  ## Trim, TrimLeft, TrimRight, and TrimSpace
   102  
   103  > **Note:** In Loki 2.1 [trim](#trim), [trimAll](#trimall), [trimSuffix](#trimsuffix) and [trimPrefix](#trimprefix) have been added with a different signature for better pipeline chaining.
   104  
   105  `Trim` returns a slice of the string s with all leading and
   106  trailing Unicode code points contained in cutset removed.
   107  
   108  Signature: `Trim(value, cutset string) string`
   109  
   110  `TrimLeft` and `TrimRight` are the same as `Trim` except that it trims only leading and trailing characters respectively.
   111  
   112  ```template
   113  `{{ Trim .query ",. " }}`
   114  `{{ TrimLeft .uri ":" }}`
   115  `{{ TrimRight .path "/" }}`
   116  ```
   117  
   118  `TrimSpace` TrimSpace returns string s with all leading
   119  and trailing white space removed, as defined by Unicode.
   120  
   121  Signature: `TrimSpace(value string) string`
   122  
   123  ```template
   124  {{ TrimSpace .latency }}
   125  ```
   126  
   127  `TrimPrefix` and `TrimSuffix` will trim respectively the prefix or suffix supplied.
   128  
   129  Signature:
   130  
   131  - `TrimPrefix(value string, prefix string) string`
   132  - `TrimSuffix(value string, suffix string) string`
   133  
   134  ```template
   135  {{ TrimPrefix .path "/" }}
   136  ```
   137  
   138  ## regexReplaceAll and regexReplaceAllLiteral
   139  
   140  `regexReplaceAll` returns a copy of the input string, replacing matches of the Regexp with the replacement string replacement. Inside string replacement, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first sub-match. See the golang [Regexp.replaceAll documentation](https://golang.org/pkg/regexp/#Regexp.ReplaceAll) for more examples.
   141  
   142  ```template
   143  `{{ regexReplaceAll "(a*)bc" .some_label "${1}a" }}`
   144  ```
   145  
   146  `regexReplaceAllLiteral` function returns a copy of the input string and replaces matches of the Regexp with the replacement string replacement. The replacement string is substituted directly, without using Expand.
   147  
   148  ```template
   149  `{{ regexReplaceAllLiteral "(ts=)" .timestamp "timestamp=" }}`
   150  ```
   151  
   152  You can combine multiple functions using pipe. For example, to strip out spaces and make the request method in capital, you would write the following template: `{{ .request_method | TrimSpace | ToUpper }}`.
   153  
   154  ## lower
   155  
   156  > Added in Loki 2.1
   157  
   158  Use this function to convert to lower case.
   159  
   160  Signature:
   161  
   162  `lower(string) string`
   163  
   164  Examples:
   165  
   166  ```template
   167  "{{ .request_method | lower }}"
   168  `{{ lower  "HELLO"}}`
   169  ```
   170  
   171  The last example will return `hello`.
   172  
   173  ## upper
   174  
   175  > Added in Loki 2.1
   176  
   177  Use this function to convert to upper case.
   178  
   179  Signature:
   180  
   181  `upper(string) string`
   182  
   183  Examples:
   184  
   185  ```template
   186  "{{ .request_method | upper }}"
   187  `{{ upper  "hello"}}`
   188  ```
   189  
   190  This results in `HELLO`.
   191  
   192  ## title
   193  
   194  > **Note:** Added in Loki 2.1.
   195  
   196  Convert to title case.
   197  
   198  Signature:
   199  
   200  `title(string) string`
   201  
   202  Examples:
   203  
   204  ```template
   205  "{{.request_method | title}}"
   206  `{{ title "hello world"}}`
   207  ```
   208  
   209  The last example will return `Hello World`.
   210  
   211  ## trunc
   212  
   213  > **Note:** Added in Loki 2.1.
   214  
   215  Truncate a string and add no suffix.
   216  
   217  Signature:
   218  
   219  `trunc(count int,value string) string`
   220  
   221  Examples:
   222  
   223  ```template
   224  "{{ .path | trunc 2 }}"
   225  `{{ trunc 5 "hello world"}}`   // output: hello
   226  `{{ trunc -5 "hello world"}}`  // output: world
   227  ```
   228  
   229  ## substr
   230  
   231  > **Note:** Added in Loki 2.1.
   232  
   233  Get a substring from a string.
   234  
   235  Signature:
   236  
   237  `substr(start int,end int,value string) string`
   238  
   239  If start is < 0, this calls value[:end].
   240  If start is >= 0 and end < 0 or end bigger than s length, this calls value[start:]
   241  Otherwise, this calls value[start, end].
   242  
   243  Examples:
   244  
   245  ```template
   246  "{{ .path | substr 2 5 }}"
   247  `{{ substr 0 5 "hello world"}}`  // output: hello
   248  `{{ substr 6 11 "hello world"}}` // output: world
   249  ```
   250  
   251  ## replace
   252  
   253  > **Note:** Added in Loki 2.1.
   254  
   255  This function performs simple string replacement.
   256  
   257  Signature: `replace(old string, new string, src string) string`
   258  
   259  It takes three arguments:
   260  
   261  - `old` string to replace
   262  - `new` string to replace with
   263  - `src` source string
   264  
   265  Examples:
   266  
   267  ```template
   268  {{ .cluster | replace "-cluster" "" }}
   269  {{ replace "hello" "world" "hello world" }}
   270  ```
   271  
   272  The last example will return `world world`.
   273  
   274  ## trim
   275  
   276  > **Note:** Added in Loki 2.1.
   277  
   278  The trim function removes space from either side of a string.
   279  
   280  Signature: `trim(string) string`
   281  
   282  Examples:
   283  
   284  ```template
   285  {{ .ip | trim }}
   286  {{ trim "   hello    " }} // output: hello
   287  ```
   288  
   289  ## trimAll
   290  
   291  > **Note:** Added in Loki 2.1.
   292  
   293  Use this function to remove given characters from the front or back of a string.
   294  
   295  Signature: `trimAll(chars string,src string) string`
   296  
   297  Examples:
   298  
   299  ```template
   300  {{ .path | trimAll "/" }}
   301  {{ trimAll "$" "$5.00" }} // output: 5.00
   302  ```
   303  
   304  ## trimSuffix
   305  
   306  > **Note:** Added in Loki 2.1.
   307  
   308  Use this function to trim just the suffix from a string.
   309  
   310  Signature: `trimSuffix(suffix string, src string) string`
   311  
   312  Examples:
   313  
   314  ```template
   315  {{  .path | trimSuffix "/" }}
   316  {{ trimSuffix "-" "hello-" }} // output: hello
   317  ```
   318  
   319  ## trimPrefix
   320  
   321  > **Note:** Added in Loki 2.1.
   322  
   323  Use this function to trim just the prefix from a string.
   324  
   325  Signature: `trimPrefix(prefix string, src string) string`
   326  
   327  Examples:
   328  
   329  ```template
   330  {{  .path | trimPrefix "/" }}
   331  {{ trimPrefix "-" "-hello" }} // output: hello
   332  ```
   333  
   334  ## indent
   335  
   336  > **Note:** Added in Loki 2.1.
   337  
   338  The indent function indents every line in a given string to the specified indent width. This is useful when aligning multi-line strings.
   339  
   340  Signature: `indent(spaces int,src string) string`
   341  
   342  ```template
   343  {{ indent 4 .query }}
   344  ```
   345  
   346  This indents each line contained in the `.query` by four (4) spaces.
   347  
   348  ## nindent
   349  
   350  > **Note:** Added in Loki 2.1.
   351  
   352  The nindent function is the same as the indent function, but prepends a new line to the beginning of the string.
   353  
   354  Signature: `nindent(spaces int,src string) string`
   355  
   356  ```template
   357  {{ nindent 4 .query }}
   358  ```
   359  
   360  This will indent every line of text by 4 space characters and add a new line to the beginning.
   361  
   362  ## repeat
   363  
   364  > **Note:** Added in Loki 2.1.
   365  
   366  Use this function to repeat a string multiple times.
   367  
   368  Signature: `repeat(c int,value string) string`
   369  
   370  ```template
   371  {{ repeat 3 "hello" }} // output: hellohellohello
   372  ```
   373  
   374  ## contains
   375  
   376  > **Note:** Added in Loki 2.1.
   377  
   378  Use this function to test to see if one string is contained inside of another.
   379  
   380  Signature: `contains(s string, src string) bool`
   381  
   382  Examples:
   383  
   384  ```template
   385  {{ if .err contains "ErrTimeout" }} timeout {{end}}
   386  {{ if contains "he" "hello" }} yes {{end}}
   387  ```
   388  
   389  ## hasPrefix and hasSuffix
   390  
   391  > **Note:** Added in Loki 2.1.
   392  
   393  The `hasPrefix` and `hasSuffix` functions test whether a string has a given prefix or suffix.
   394  
   395  Signatures:
   396  
   397  - `hasPrefix(prefix string, src string) bool`
   398  - `hasSuffix(suffix string, src string) bool`
   399  
   400  Examples:
   401  
   402  ```template
   403  {{ if .err hasSuffix "Timeout" }} timeout {{end}}
   404  {{ if hasPrefix "he" "hello" }} yes {{end}}
   405  ```
   406  
   407  ## add
   408  
   409  > **Note:** Added in Loki 2.3.
   410  
   411  Sum numbers. Supports multiple numbers
   412  
   413  Signature: `func(i ...interface{}) int64`
   414  
   415  ```template
   416  {{ add 3 2 5 }} // output: 10
   417  ```
   418  
   419  ## sub
   420  
   421  > **Note:** Added in Loki 2.3.
   422  
   423  Subtract numbers.
   424  
   425  Signature: `func(a, b interface{}) int64`
   426  
   427  ```template
   428  {{ sub 5 2 }} // output: 3
   429  ```
   430  
   431  ## mul
   432  
   433  > **Note:** Added in Loki 2.3.
   434  
   435  Mulitply numbers. Supports multiple numbers.
   436  
   437  Signature: `func(a interface{}, v ...interface{}) int64`
   438  
   439  ```template
   440  {{ mul 5 2 3}} // output: 30
   441  ```
   442  
   443  ## div
   444  
   445  > **Note:** Added in Loki 2.3.
   446  
   447  Integer divide numbers.
   448  
   449  Signature: `func(a, b interface{}) int64`
   450  
   451  ```template
   452  {{ div 10 2}} // output: 5
   453  ```
   454  
   455  ## addf
   456  
   457  > **Note:** Added in Loki 2.3.
   458  
   459  Sum numbers. Supports multiple numbers.
   460  
   461  Signature: `func(i ...interface{}) float64`
   462  
   463  ```template
   464  {{ addf 3.5 2 5 }} // output: 10.5
   465  ```
   466  
   467  ## subf
   468  
   469  > **Note:** Added in Loki 2.3.
   470  
   471  Subtract numbers. Supports multiple numbers.
   472  
   473  Signature: `func(a interface{}, v ...interface{}) float64`
   474  
   475  ```template
   476  {{ subf  5.5 2 1.5 }} // output: 2
   477  ```
   478  
   479  ## mulf
   480  
   481  > **Note:** Added in Loki 2.3.
   482  
   483  Mulitply numbers. Supports multiple numbers
   484  
   485  Signature: `func(a interface{}, v ...interface{}) float64`
   486  
   487  ```template
   488  {{ mulf 5.5 2 2.5 }} // output: 27.5
   489  ```
   490  
   491  ## divf
   492  
   493  > **Note:** Added in Loki 2.3.
   494  
   495  Divide numbers. Supports multiple numbers.
   496  
   497  Signature: `func(a interface{}, v ...interface{}) float64`
   498  
   499  ```template
   500  {{ divf 10 2 4}} // output: 1.25
   501  ```
   502  
   503  ## mod
   504  
   505  > **Note:** Added in Loki 2.3.
   506  
   507  Modulo wit mod.
   508  
   509  Signature: `func(a, b interface{}) int64`
   510  
   511  ```template
   512  {{ mod 10 3}} // output: 1
   513  ```
   514  
   515  ## max
   516  
   517  > **Note:** Added in Loki 2.3.
   518  
   519  Return the largest of a series of integers:
   520  
   521  Signature: `max(a interface{}, i ...interface{}) int64`
   522  
   523  ```template
   524  {{ max 1 2 3 }} //output 3
   525  ```
   526  
   527  ## min
   528  
   529  > **Note:** Added in Loki 2.3.
   530  
   531  Return the smallest of a series of integers.
   532  
   533  Signature: `min(a interface{}, i ...interface{}) int64`
   534  
   535  ```template
   536  {{ max 1 2 3 }} //output 1
   537  ```
   538  
   539  ## maxf
   540  
   541  > **Note:** Added in Loki 2.3.
   542  
   543  Return the largest of a series of floats:
   544  
   545  Signature: `maxf(a interface{}, i ...interface{}) float64`
   546  
   547  ```template
   548  {{ maxf 1 2.5 3 }} //output 3
   549  ```
   550  
   551  ## minf
   552  
   553  > **Note:** Added in Loki 2.3.
   554  
   555  Return the smallest of a series of floats.
   556  
   557  Signature: `minf(a interface{}, i ...interface{}) float64`
   558  
   559  ```template
   560  {{ minf 1 2.5 3 }} //output 1.5
   561  ```
   562  
   563  ## ceil
   564  
   565  > **Note:** Added in Loki 2.3.
   566  
   567  Returns the greatest float value greater than or equal to input value
   568  
   569  Signature: `ceil(a interface{}) float64`
   570  
   571  ```template
   572  {{ ceil 123.001 }} //output 124.0
   573  ```
   574  
   575  ## floor
   576  
   577  > **Note:** Added in Loki 2.3.
   578  
   579  Returns the greatest float value less than or equal to input value
   580  
   581  Signature: `floor(a interface{}) float64`
   582  
   583  ```template
   584  {{ floor 123.9999 }} //output 123.0
   585  ```
   586  
   587  ## round
   588  
   589  > **Note:** Added in Loki 2.3.
   590  
   591  Returns a float value with the remainder rounded to the given number of digits after the decimal point.
   592  
   593  Signature: `round(a interface{}, p int, rOpt ...float64) float64`
   594  
   595  ```template
   596  {{ round 123.555555 3 }} //output 123.556
   597  ```
   598  
   599  We can also provide a `roundOn` number as third parameter
   600  
   601  ```template
   602  {{ round 123.88571428571 5 .2 }} //output 123.88572
   603  ```
   604  
   605  With default `roundOn` of `.5` the above value would be `123.88571`
   606  
   607  ## int
   608  
   609  > **Note:** Added in Loki 2.3.
   610  
   611  Convert value to an int.
   612  
   613  Signature: `toInt(v interface{}) int`
   614  
   615  ```template
   616  {{ "3" | int }} //output 3
   617  ```
   618  
   619  ## float64
   620  
   621  > **Note:** Added in Loki 2.3.
   622  
   623  Convert to a float64.
   624  
   625  Signature: `toFloat64(v interface{}) float64`
   626  
   627  ```template
   628  {{ "3.5" | float64 }} //output 3.5
   629  ```
   630  
   631  ## fromJson
   632  
   633  > **Note:** Added in Loki 2.3.
   634  
   635  fromJson decodes a JSON document into a structure. If the input cannot be decoded as JSON the function will return an empty string.
   636  
   637  ```template
   638  fromJson "{\"foo\": 55}"
   639  ```
   640  
   641  Example of a query to print a newline per queries stored as a json array in the log line:
   642  
   643  ```logql
   644  {job="loki/querier"} |= "finish in prometheus" | logfmt | line_format "{{ range $q := fromJson .queries }} {{ $q.query }} {{ end }}"
   645  ```
   646  
   647  ## now
   648  
   649  `now` returns the current local time.
   650  
   651  ```template
   652  {{ now }}
   653  ```
   654  
   655  ## toDate
   656  
   657  `toDate` parses a formatted string and returns the time value it represents.
   658  
   659  ```template
   660  {{ toDate "2006-01-02" "2021-11-02" }}
   661  ```
   662  
   663  ## date
   664  
   665  `date` returns a textual representation of the time value formatted according to the provided [golang datetime layout](https://pkg.go.dev/time#pkg-constants).
   666  
   667  ```template
   668  { date "2006-01-02" now }}
   669  ```
   670  
   671  ## unixEpoch
   672  
   673  `unixEpoch` returns the number of seconds elapsed since January 1, 1970 UTC.
   674  
   675  ```template
   676  { unixEpoch now }}
   677  ```
   678  
   679  Example of a query to filter Loki querier jobs which create time is 1 day before:
   680  ```logql
   681  {job="loki/querier"} | label_format nowEpoch=`{{(unixEpoch now)}}`,createDateEpoch=`{{unixEpoch (toDate "2006-01-02" .createDate)}}` | label_format dateTimeDiff="{{sub .nowEpoch .createDateEpoch}}" | dateTimeDiff > 86400
   682  ```
   683  
   684  ## default
   685  
   686  `default` checks whether the string(`src`) is set, and returns default(`d`) if not set.
   687  
   688  Signature: `default(d string, src string) string`
   689  
   690  Examples:
   691  
   692  ```template
   693  {{ default "-" "" }} // output: -
   694  {{ default "-" "foo" }} // output: foo
   695  ```
   696  
   697  Example of a query to print a `-` if the `http_request_headers_x_forwarded_for` label is empty:
   698  ```logql
   699  {job="access_log"} | json | line_format `{{.http_request_headers_x_forwarded_for | default "-"}}`
   700  ```