Syntax for new alert templates

更新时间:
复制 MD 格式

Simple Log Service supports two versions of alert template syntax: new and original. The new syntax uses a Python-like approach for more flexible, advanced custom rendering of alert notifications.

Overview

Compared with the original alert templates, the new alert templates use a Python-like syntax for more flexible custom rendering logic and optimized notification content and styles, such as Markdown character escaping. Key advantages include:

  • Dynamic rendering based on alert severity levels, using different colored fonts to distinguish severity levels.

  • Iterative rendering of alert query results into a list or table in an email.

  • Built-in functions for Base64 encoding/decoding and arithmetic operations on numeric values.

The new syntax is fully compatible with the original syntax but uses different types, values, and styles for alert attributes. We recommend that you use only the new syntax and avoid mixing the two.

Quick start

The following examples show notification content defined in the new alert templates.

  • Alert content:

    {
        "alert_id": "test-alert",
        "alert_name": "PV/UV Alert",
        "project": "project-1",
        "status": "firing",
        "severity": 6,
        "labels": {
            "app": "nginx",
            "host": "host-1"
        },
        "results": [
            {
                "project": "project-1",
                "logstore": "logstore-1",
                "query": "* | select count(*) as pv"
            },
            {
                "project": "project-2",
                "logstore": "logstore-2",
                "query": "* | select count(distinct user_id) as uv"
            }
        ]
    }
  • Alert template configuration:

    - Alert ID: {{ alert.alert_id }}
    - Alert Name: {{ alert.alert_name }}
    - Project: {{ alert.project }}
    - Status: {% if alert.status == "firing" %}FIRING{% else %}RESOLVED{% endif %}
    - Labels:
    {%- for key, val in alert.labels.items() %}
        - {{ key }}: {{ val }}
    {%- endfor %}
    - Query: {{ alert.results[0].query }}
  • Output result:

    - Alert ID: test-alert
    - Alert Name: PV/UV Alert
    - Project: project-1
    - Status: FIRING
    - Labels:
        - app: nginx
        - host: host-1
    - Query: * | select count(*) as pv

Basic syntax

Data types

The following table describes the data types supported by the Python-like syntax.

Data type

Description

Number

Supported numbers include integers and floating-point numbers. Examples: 3 and -1.

String

A string must be enclosed in single quotation marks ('') or double quotation marks (""). Examples: "foo" and 'bar'.

If a string contains special characters, a backslash (\) must be used to escape the special characters. For example, \foo must be escaped into "\\foo".

Boolean

Supported Boolean values are True and False.

Null

None.

List

A list can be referred to as an array or a slice in other programming languages. Example: ['foo', 'bar'].

Dictionary

A dictionary can be referred to as an object in other programming languages. Example: {'foo': 'bar'}.

Delimiters

Delimiter

Use scenario

Example

{{ }}

Marks the start and end of a variable or expression.

  • Number: {{ 123 }}

  • String: {{ "abc" }} or {{ 'xyz' }}

    A string must be enclosed in double quotation marks ("") or single quotation marks ('').

  • Variable: {{ alert.alert_name }}

  • Expression: {{ alert.project + '/' + alert.alert_id }}

{% %}

Marks the start and end of a statement.

{% if alert.status == 'firing' %}FIRING{% else %}RESOLVED{% endif %}

{# #}

Marks the start and end of a comment. Comments are not included in alert notifications.

{# this is a comment #}

Removal of empty strings

By default, Simple Log Service ignores spaces between a delimiter and the expression inside. For example, both {{ 23 }} < {{ 45 }} and {{23}} < {{45}} render as 23 < 45. However, whitespace characters (spaces, tabs, and line feeds) outside delimiters are preserved. For example, {{ 23 }} < {{ 45 }} renders as 23 < 45, not 23<45.

To remove unwanted whitespace to the left or right of a delimiter, add a hyphen (-) next to the delimiter. For example, {{ 23 -}} < {{- 45 }} renders as 23<45.

  • {{-, {{%-, and {#- remove all whitespace to the left of the delimiter.

  • -}}, -%}, and -%} remove all whitespace to the right of the delimiter.

Important
  • No spaces are allowed between the hyphen (-) and the delimiter. For example, the hyphen in {{- 3 }} is valid and renders the number as 3. However, the hyphen in {{ - 3 }} is treated as a minus sign and renders the number as -3.

  • The hyphen only affects whitespace outside delimiters, not content inside. For example, {{ "hello " }} {{- "world"}} renders as hello world.

Conditional statements

Conditional statements evaluate parameter values and logical expressions to control rendering.

  • If the if clause is followed by a constant or variable, it is evaluated as true or false. Boolean false, number 0, empty string "", null, empty array [], and empty object {} evaluate to false. All other values evaluate to true.

  • If the if clause is followed by a logical expression, the expression result is evaluated as true or false. For example, {{ if alert.severity >= 8 }} checks whether the alert severity is 8 or higher.

The following table describes the supported conditional flows.

Control flow

Example

if

{% if alert.severity >= 8 %}
Critical alert
{% endif %}

if-else

{% if alert.severity >= 8 %}
Critical alert
{% else %}
Normal alert
{% endif %}

if-elif

{% if alert.severity >= 8 %}
Critical alert
{% elif alert.severity >= 4 %}
Normal alert
{% endif %}

if-elif-else

{% if alert.severity >= 8 %}
Critical alert
{% elif alert.severity >= 4 %}
Normal alert
{% else %}
Notification
{% endif %}

Nested statement

{% if alert.severity >= 8 %}
Critical alert
{% else %}
{% if alert.severity >= 4 %}
Normal alert
{% else %}
Notification
{% endif %}
{% endif %}

Iterations

Loop statements iterate over arrays and objects. The following table describes the supported loop statements.

Loop statement

Example

Loop statements on arrays

{% for result in alert.results %}
{{ result }}
{% endfor %}

Loop statements with subscripts on arrays

The enumerate function iterates over array subscripts. For more information about the enumerate function, see Built-in functions in alert templates.

{% for index, result in enumerate(alert.results) %}
{{ index }}: {{ result }}
{% endfor %}

Subscripts start at 0 by default. Use the start parameter in the enumerate function to specify a custom start subscript. Example:

{% for index, result in enumerate(alert.results, start=1) %}
{{ index }}: {{ result }}
{% endfor %}

Loop statements on objects

The items() function converts an object into an array of key-value pairs in Key:Value format for iteration.

{% for key, val in alert.labels.items() %}
{{ key }}: {{ val }}
{% endfor %}

Nested statements

{% for result in alert.fire_results %}
{% for key, val in result.items() %}
{{ key }}: {{ val }}
{% endfor %}
{% endfor %}

Escape characters

To prevent Simple Log Service from parsing special character strings such as {{, you can escape them. The following example retains all content between {% raw %} and {% endraw %} as-is:

  • Alert template configuration

    {% raw %}
    {% for result in alert.results %}
    {{ result }} {% endfor %} {% endraw %}
  • Result

    {% for result in alert.results %}
    {{ result }}
    {% endfor %}

Functions

Alert templates provide built-in functions to flexibly configure notification formats and styles. For more information, see Built-in template functions.

For example, to push alert notifications in JSON format by using a webhook URL, use the following template configuration:

  • Query statement with a line feed included

    * |
    select count(*) as cnt
  • Comparison between different alert template configurations

    Item

    Alert template

    Result

    Remarks

    No functions used

    {
        "query": "{{ alert.results[0].query }}"
    }
    {
        "query": "* |
    select count(*) as pv"
    }

    The JSON format is invalid.

    The quote function used

    {
        "query": {{ quote(alert.results[0].query) }}
    }
    {
        "query": "* | \nselect count(*) as pv"
    }

    The JSON format is valid.

Filters

When nested functions such as {{ block(to_list(alert.labels)) }} become hard to read, you can use filters instead. Filters use vertical bars (|) as operators and support method chaining. Specify filters in the {{ xxx | filiter1 | filter2 | ... }} format. For example, {{ blockquote(to_list(alert.labels)) }} is equivalent to {{ alert.labels | to_list | blockquote }}.

Before using filters with a built-in function, verify that the function supports filters. Most built-in functions in the new alert templates support filters. For more information, see Built-in template functions.

Important
  • If a built-in function has no parameters, filters cannot be used.

  • If a built-in function has a single parameter, we recommend using the filter syntax. The format is {{ arg | fn }}. For example, {{ abs(-1) }} is equivalent to {{ -1 | abs }}.

  • If a built-in function has multiple parameters and all except the first have default values, filters can be used. If you need to specify values for all parameters, we recommend calling the function directly instead of using filters.

Operators

The following table describes the supported operators. For more information about operator priorities, see Operator precedence.

Category

Operator

Description

Arithmetic operations

+

Performs an addition operation.

-

Performs a subtraction operation.

*

Performs a multiplication operation.

/

Division. Returns a floating-point number.

//

Division. Returns an integer.

%

Performs a modulo operation.

Comparative operations

==

Evaluates whether a value is equal to another value.

!=

Evaluates whether a value is not equal to another value.

>

Evaluates whether a value is greater than another value.

>=

Evaluates whether a value is greater than or equal to another value.

<

Evaluates whether a value is less than another value.

<=

Evaluates whether a value is less than or equal to another value.

Logical operations

and

Specifies an AND relation.

or

Specifies an OR relation.

not

Specifies a NOT relation.

Other operations

in

Checks whether a value is included in another value and returns a Boolean value. Supports arrays, objects, and strings.

  • Array: {{ 1 in [1, 2, 3] }}

  • Object: {{ "foo" in {"foo": "bar" } }}

  • String: {{ "ll" in "hello" }}

()

Specifies a combination of operations. Example: {{ a > b and (a > c or b > c) }}.

Alert variables

In the new alert templates, alert variables use the alert.xxx format. For example, alert.project is a valid alert variable. For more information, see Variables in alert templates.

Configuration examples

  • Example 1: Display alert information based on the alert status.

    When an alert is triggered, the status, severity level, and result are provided. When an alert is cleared, only the status is provided.

    • The following template configuration does not include functions:

      {% if alert.status == "firing" %}
      - Status: <font color="#E03C39">Firing</font>
      - Severity level: {{ alert.severity | format_severity }}
      - Results: {{ alert.results | to_json }}
      {% else %}
      - Status: <font color="#72C140">Cleared</font>
      {% endif %}
    • The following template configuration includes functions:

      The format_status and format_severity functions simplify the template configuration:

      - Status: {{ alert.status | format_status }}
      {% if alert.status == "firing" %}
      - Severity level: {{ alert.severity | format_severity }}
      - Results: {{ alert.results | to_json }}
      {% endif %}
  • Example 2: Display alert information in a structured format.

    Alert labels are converted into a Markdown-formatted array.

    • The following template configuration does not include functions:

      - Project: {{ alert.project }}
      - Alert name: {{ alert.alert_name }}
      - Label:
      {%- for key, val in alert.labels.items() %}
      > - {{ key }}: {{ val }}
      {%- endfor %}
    • The following template configuration includes functions:

      The to_list and blockquote functions simplify the template configuration.

      - Project: {{ alert.project }}
      - Alert name: {{ alert.alert_name }}
      - Label:
      {{ alert.labels | to_list | blockquote }}