Skip to content

Webhook Custom Body Template


Using template syntax, you can customize the Webhook notification Body content:

  • Dynamic rendering: Use {{ field_name }} to directly insert alert fields (e.g., {{ host }}, {{ df_status }});

  • Data processing: Format data via {{ variable | function() }} (e.g., timestamp to date, number to percentage);

  • Conditional branching: Use {% if ... %} to achieve differentiated Body output under different statuses;

  • JSON output: Output JSON objects, arrays, numbers, booleans, etc., via to_json_dumps;

  • Real-time query: Embed DQL("query statement") to retrieve associated data (e.g., host IP, system information).

Basic Template Variables

The basic syntax for template variables is {{ field_name }}, which can be used to render dynamic information related to events. The following are common template variables and their purposes in Webhook custom Body:

Template Variable Type Description
date, timestamp Integer Event generation time, Unix timestamp, unit: seconds
df_status String(Enum) Event status, possible values: critical critical, error error, warning warning, ok ok, nodata nodata
df_event_id String Unique event ID
df_event_link String Event details page link address
df_title String Event title
df_message String Event content
df_dimension_tags String Event dimensions, used to identify the detection object, e.g., {"host":"web-001"}
df_dimension_tags_obj Dict Event dimension object, convenient for reading dimension fields as an object
df_monitor_id String Alert policy ID
df_monitor_name String Alert policy name
df_monitor_checker_id String Monitor ID
df_monitor_checker_name String Monitor name
df_monitor_checker_value String Detection value, i.e., the value detected by the monitor
Result Integer, Float, String, Dict, List The original detected value, same as df_monitor_checker_value as the value generated during detection, but retains the original type
Result_with_unit String Detection value with unit
df_related_data Dict Associated data
df_fault_id String Current fault round ID, value is the df_event_id of the first fault event
df_fault_status String(Enum) Current fault round status, possible values: ok ok, fault fault
df_fault_start_time Integer Current fault round start time, Unix timestamp, unit: seconds
df_fault_duration Integer Current fault round duration, unit: seconds
df_site_name String Current Guance node name
df_workspace_name String Belonging workspace name
df_workspace_uuid String Belonging workspace ID
df_label List Monitor label list
df_alert_policy_names List List of hit alert policy names
df_sent_target_types List List of alert notification target types to which this event has been sent
df_event Dict Complete event data
Fields within df_dimension_tags String Fields within df_dimension_tags are extracted to the top level, e.g., host, region

Note:

  • df_monitor_checker_value is forcibly converted to String type for compatibility;

  • If you need to preserve the original type of the detection value, it is recommended to use Result;

  • Available variables may differ depending on monitor type, event source, and notification scenario.

Template Variable Example

Assuming the monitor by is configured with region and host, the Webhook custom Body template is as follows:

{
  "title": "Monitor {{ df_monitor_checker_name }} found fault in {{ df_dimension_tags }}",
  "region": "{{ region }}",
  "host": "{{ host }}",
  "status": "{{ df_status }}",
  "value": "{{ Result }}",
  "monitor": "{{ df_monitor_checker_name }}",
  "policy": "{{ df_monitor_name }}"
}

Then, after an error event is generated, the rendered Body output is as follows:

{
  "title": "Monitor Monitor001 found fault in {\"region\":\"hangzhou\",\"host\":\"web-001\"}",
  "region": "hangzhou",
  "host": "web-001",
  "status": "error",
  "value": "90.12345",
  "monitor": "Monitor001",
  "policy": "Team001"
}

JSON Body Output

The final Webhook custom Body typically needs to output valid JSON. It is recommended to first define the JSON object and then use the to_json_dumps function to process it, to avoid JSON syntax errors such as string escaping, object/array nesting, and missing commas.

Example:

{% set json_data = {
  "event_id": df_event_id,
  "title": df_title,
  "status": df_status,
  "status_text": df_status | to_status_human,
  "event_link": df_event_link,
  "monitor": {
    "id": df_monitor_id,
    "name": df_monitor_name,
    "checker_id": df_monitor_checker_id,
    "checker_name": df_monitor_checker_name
  },
  "dimension": {
    "raw": df_dimension_tags,
    "object": df_dimension_tags_obj,
    "pretty": df_dimension_tags | to_pretty_tags
  },
  "value": {
    "raw": Result,
    "with_unit": Result_with_unit,
    "type": Result | type_name
  }
} %}
{{ json_data | to_json_dumps }}

The output result is as follows:

{
  "event_id": "event-xxxxx",
  "title": "High CPU usage",
  "status": "error",
  "status_text": "Error",
  "event_link": "https://console.guance.com/keyevents/monitor/events/event-xxxxx",
  "monitor": {
    "id": "altpl_xxxxx",
    "name": "Team001",
    "checker_id": "rul_xxxxx",
    "checker_name": "Monitor001"
  },
  "dimension": {
    "raw": "{\"region\":\"hangzhou\",\"host\":\"web-001\"}",
    "object": {
      "region": "hangzhou",
      "host": "web-001"
    },
    "pretty": "region:hangzhou, host:web-001"
  },
  "value": {
    "raw": 90.12345,
    "with_unit": "90.12345%",
    "type": "float"
  }
}

Field-by-Field JSON Rendering

You can also render JSON field by field. In this case, pay attention to the field types:

{
  "event_id": "{{ df_event_id }}",
  "status": "{{ df_status }}",
  "status_text": "{{ df_status | to_status_human }}",
  "checker_name": "{{ df_monitor_checker_name }}",
  "dimension": {{ df_dimension_tags_obj | to_json_dumps }},
  "value": {{ Result | to_json_dumps }},
  "related_data": {{ df_related_data | to_json_dumps }}
}

Explanation:

  • String fields can be placed in double quotes, e.g., "{{ df_status }}";

  • Objects, arrays, numbers, and booleans are recommended to use to_json_dumps;

  • It is not recommended to write objects or arrays as "{{ df_related_data }}", otherwise the receiver will get a string instead of a JSON object.

Special Scenario Variables

User Access Metrics Detection

In user access metrics detection, in addition to the general template variables mentioned above, the following template variables are additionally supported:

Template Variable Type Description
app_id String Application ID
app_name String Application name
app_type String Application type

Special Character Field Handling

If the Dimension field in the detection configuration contains special characters (e.g., -, @), such as host-name, @level, they cannot be used directly as normal variable names, which will cause template rendering to fail.

Incorrect writing:

{{ host-name }}
{{ @level }}

The solution is to use the following format for reference:

{{ df_event["host-name"] }}
{{ df_event["@level"] }}
{{ df_dimension_tags_obj["host-name"] }}
{{ df_dimension_tags_obj["@level"] }}

Template Functions

In addition to directly displaying field values from events, you can also use template functions to further process field values and optimize output.

The basic syntax is as follows:

{{ <template_variable> | <template_function> }}
{{ <template_variable> | <template_function>(parameter) }}

Specific examples are as follows:

Event generation time: {{ date | to_datetime }}

If you need to perform operations on template variables before using template functions, do not forget to add parentheses, e.g.:

CPU usage: {{ (Result * 100) | to_round(2) }}

The list of available template functions is as follows:

Template Function Parameters Description
to_datetime tz="Asia/Shanghai" Convert Unix second-level timestamp or ISO8601 date string to date-time string
to_date_range_human lang="zh" Convert second-level duration to human-readable form, e.g., 1 day 2 hours 3 minutes 1 second
to_status_human lang="zh" Convert df_status to human-readable status
to_fixed ndigits=0 Output number with fixed decimal places
to_round ndigits=0 Round number to specified decimal places
to_percent ndigits=0 Convert decimal to percentage form
to_pretty_tags separators=(':', ', ') Convert dict or JSON string formatted tags to human-readable tag text
limit_lines lines=3, chars=None Limit output lines, can also limit characters per line
limit_chars / limit_text chars=50 Limit output characters, limit_text is an alias for limit_chars
type_name None Output data type name
to_int None Convert to integer
to_float None Convert to float
to_str None Convert to string
to_json_dumps indent=None Convert dict, list, etc., data to JSON serialized string
is_error None Determine if object is an error, often used to determine if embedded DQL executed normally
length None Get length of string, list, dict, etc.
replace old, new, count=-1 Replace string content, count=-1 means replace all
abs None Get absolute value of number

Template Function Example

{% set body = {
  "object": df_dimension_tags | to_pretty_tags,
  "time": date | to_datetime,
  "status": df_status | to_status_human,
  "value": Result | to_fixed(2),
  "percent": Result | to_percent(1),
  "duration": df_fault_duration | to_date_range_human,
  "message": df_message | limit_lines(3, 80)
} %}
{{ body | to_json_dumps }}

Template Branching

Conditional branching can be used to achieve differentiated Body output under different statuses.

Basic syntax is as follows:

{% if condition %}
  ...
{% elif condition %}
  ...
{% else %}
  ...
{% endif %}

Template Branching Example

{% set level = "info" %}
{% if df_status == "critical" %}
  {% set level = "critical" %}
{% elif df_status == "error" %}
  {% set level = "error" %}
{% elif df_status == "warning" %}
  {% set level = "warning" %}
{% elif df_status == "nodata" %}
  {% set level = "nodata" %}
{% endif %}

{% set body = {
  "level": level,
  "status": df_status,
  "status_text": df_status | to_status_human,
  "title": df_title,
  "event_link": df_event_link
} %}
{{ body | to_json_dumps }}

Embedded DQL Query Function

When template variables alone cannot meet rendering requirements, you can use the embedded DQL query function to supplement query data. Embedded DQL will execute DQL in this workspace, within this detection time range, and usually use the first piece of query result data as a template variable.

The calling format is as follows:

{% set dql_data = DQL("DQL statement", parameter 1, parameter 2) %}

Embedded DQL Query Example

{% set host_info = DQL("O::HOST:(host_ip, os) { region = ?, host = ? }", region, host) %}

{% set body = {
  "host": host,
  "region": region,
  "host_ip": host_info.host_ip,
  "os": host_info.os,
  "status": df_status,
  "event_link": df_event_link
} %}
{{ body | to_json_dumps }}

Embedded DQL Query Function Details

  • Embedded DQL queries should be placed at the beginning of the template;

  • Parameter placeholders ? in the DQL statement will be automatically escaped when replaced with specific values;

  • When passing template variables to DQL, write the variable name directly in the parameter part, e.g., host; do not write it as {{ host }};

  • The query result variable name should not conflict with existing template variables or template functions;

  • If functions are used to process fields in DQL, it is recommended to use AS to specify field aliases for easy template reading;

  • If DQL query result field names contain special characters, use the form {{ host_info["host-name"] }} to read them;

  • Can be combined with is_error to determine if DQL executed normally.

Complete Body Example

The following example is suitable for sending alert events to an external event center:

{% set is_recovery = df_status == "ok" %}
{% set priority = "P0" if df_status == "critical" else ("P1" if df_status in ["error", "nodata"] else ("P2" if df_status == "warning" else "INFO")) %}

{% set body = {
  "source": "guance",
  "event_id": df_event_id,
  "event_link": df_event_link,
  "title": df_title,
  "status": df_status,
  "status_text": df_status | to_status_human,
  "priority": priority,
  "is_recovery": is_recovery,
  "monitor": {
    "policy_id": df_monitor_id,
    "policy_name": df_monitor_name,
    "checker_id": df_monitor_checker_id,
    "checker_name": df_monitor_checker_name
  },
  "object": {
    "tags": df_dimension_tags_obj,
    "text": df_dimension_tags | to_pretty_tags
  },
  "value": {
    "raw": Result,
    "with_unit": Result_with_unit,
    "fixed_2": Result | to_fixed(2)
  },
  "fault": {
    "fault_id": df_fault_id,
    "fault_status": df_fault_status,
    "start_time": df_fault_start_time | to_datetime,
    "duration_seconds": df_fault_duration,
    "duration_text": df_fault_duration | to_date_range_human
  },
  "notify": {
    "alert_policy_names": df_alert_policy_names,
    "sent_target_types": df_sent_target_types
  }
} %}
{{ body | to_json_dumps }}

Notes

  • The final rendering result of the Webhook custom Body must be valid JSON;

  • If field values may contain double quotes, line breaks, or special characters, it is recommended to use to_json_dumps for output;

  • Do not forcibly wrap objects, arrays, numbers, or booleans into strings;

  • When debugging templates, it is recommended to first verify the rendering result with a few fields, then gradually add complex fields and conditional branches;

  • The Webhook custom Body template is only responsible for rendering the request Body; configuration such as request address and request headers is still maintained in the Webhook notification object.

Feedback

Is this page helpful? ×