Skip to content

Custom Event Notification Template


With template syntax, you can customize event notification content:

  • Dynamic rendering: Use {{ field_name }} to insert alert fields directly (such as {{ host }}, {{ df_status }});
  • Data processing: Use {{ variable | function() }} to format data (such as converting timestamps to dates or values to percentages);
  • Conditional branches: Use {% if ... %} to send different notifications for different statuses;
  • Real-time queries: Embed DQL ("query statement") to obtain related data (such as host IP and application information).

Template Validation and Preview

The Event Content, No Data Event Content of monitors, and the Event Content of Smart Monitors support syntax validation. After editing, move focus out of the input box, or when you save the monitor, the system checks the template and flags syntax issues.

After syntax validation passes, click the preview button in the event content editor, enter test values for variables as needed, and then click Preview to verify the rendered result. Standard monitors preview both the current title and content, while Smart Monitors preview the event content. You can switch test values for variables such as df_status to check conditional branches such as alert and recovery.

Preview is used to check the template effect. Actual alerts are based on data at the time the event occurs. When the template contains embedded DQL, preview reads related data from the current workspace.

Basic Template Variables

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

Template Variable Type Description
date, timestamp Integer Event generation time. Unit: seconds
df_date_range Integer Time range. Unit: seconds
df_check_range_start Integer Detection range start time. Unix timestamp in seconds
df_check_range_end Integer Detection range end time. Unix timestamp in seconds
df_status String(Enum) Common statuses of monitoring events:
Fatal fatal
Critical critical
Error error
Warning warning
Info info
OK ok
No Data nodata. For all values, see Event Fields Reference. For severity mappings, see Event Severity
df_event_id String Unique event ID
df_event_link String Link to the event details page
df_dimension_tags String Event dimension. Used to identify the detection object

Example: {"host":"web-001"}
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, that is, the value detected by the monitor

❗️The detection value is forcibly converted to String type to ensure compatibility
df_monitor_checker_event_ref String Monitor event association.
Calculated from the monitor ID and event df_dimension_tags
df_fault_id String Current fault ID, which is the df_event_id of the first fault event
df_fault_status String(Enum) Current fault status, a redundant field of df_status. Possible values are:

  • OK ok
  • Fault fault
  • df_fault_start_time Integer Current fault start time. Unix timestamp in seconds
    df_fault_duration Integer Current fault duration. Unit: seconds
    df_user_id String User ID of the operator when manually recovering
    df_user_name String User name of the operator when manually recovering
    df_user_email String User email of the operator when manually recovering
    df_crontab_exec_mode String(Enum) Monitor running mode. Possible values are:

  • Auto-triggered crontab
  • Manual execution manual
  • df_site_name String Current Guance node name
    df_workspace_name String Workspace name
    df_workspace_uuid String Workspace ID
    df_label List Monitor tag list
    df_check_condition Dict Satisfied detection condition
    df_check_detail Dict Applies to mutation detection and represents the original value for mutation comparison. Contains three fields:

  • Displayed detection value (change_value)
  • Comparison value (comparison_value)
  • Change value (detection_value)
  • df_check_condition.operator String Operator of the satisfied detection condition, such as >, >=, etc.
    df_check_condition.operands List List of operands for the satisfied detection condition.
    Usually there is only 1 operand, but operators such as between have 2 operands
    df_check_condition.operands[#] Integer, Float Operand of the satisfied detection condition
    Result Integer, Float Detected value. Like df_monitor_checker_value, it is generated at detection time, but its type is the original type at detection time and is not forcibly converted to String
    Fields in df_dimension_tags String Each field in df_dimension_tags is extracted
    df_event Dict Complete event data
    df_studio_env_name Current environment name
    df_studio_console_base_url Current environment console URL
    df_studio_monitor_base_link Current environment monitor URL

    Template Variable Example

    Suppose the monitor's by is configured with region and host, and the event content template is as follows:

    Event name:

    Monitor {{ df_monitor_checker_name }} detected a fault in {{ df_dimension_tags }}
    

    Event content:

    - Region: {{ region }}
    - Host: {{ host }}
    - Status: {{ df_status }}
    - Detection value: {{ Result }}
    - Monitor: {{ df_monitor_checker_name }} (Alert Policy: {{ df_monitor_name }})
    

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

    Output event name:

    Monitor monitor-001 detected a fault in {"region":"hangzhou","host":"web-001"}
    

    Output event content:

    - Region: hangzhou
    - Host: web-001
    - Status: error
    - Detection value: 90.12345
    - Monitor: monitor-001 (Alert Policy: team-001)
    

    Special Case Variables

    RUM Metric Detection

    In RUM metric detection, in addition to the general template variables above, the following template variables are also supported:

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

    Handling Fields with Special Characters

    If the Dimension field in the detection configuration contains special characters (such as - and @), for example host-name or @level, it cannot be used directly as a normal variable name and will cause template rendering to fail.

    To resolve this, reference the fields in the following format:

    • Use {{ df_event['host-name'] }} instead of {{ host-name }}

    • Use {{ df_event['@level'] }} instead of {{ @level }}

    Template Functions

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

    The basic syntax is as follows:

    {{ <template variable> | <template function> }}
    

    Specific example:

    Event generation time: {{ date | to_datetime }}
    

    If a template function requires parameters, the syntax is as follows:

    Event generation time: {{ date | to_datetime('America/Chicago') }}
    
    Warning

    If you need to perform operations on template variables before using a template function, remember to add parentheses, for example:

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

    The available template functions are listed below:

    Template Function Parameter Description
    to_datetime Time zone Converts a timestamp to a date (default time zone: Asia/Shanghai)
    Example: {{ date | to_datetime }}
    Output: 2022-01-01 01:23:45
    to_date_range_human Converts df_fault_duration to a human-readable form
    Example: {{ df_fault_duration | to_date_range_human }}
    Output: X days Y hours Z minutes W seconds
    to_status_human Converts df_status to a human-readable form
    Example: {{ df_status | to_status_human }}
    Output: Critical
    to_fixed Decimal places Outputs a number with a fixed number of decimal places (default: 0 decimal places)
    Example: {{ Result | to_fixed(3) }}
    Output: 1.230
    to_round Decimal places Rounds a number (default: 0 decimal places)
    Example: {{ Result | to_round(2) }}
    Output: 1.24
    to_percent Decimal places Outputs a decimal as a percentage (default: 0 decimal places)
    Example: {{ Result | to_percent(1) }}
    Output: 12.3%
    to_pretty_tags Formats tags for output
    Example: {{ df_dimension_tags | to_pretty_tags }}
    Output: region:hanghzou, host:web-001
    limit_lines Limits the number of lines
    limit_chars / limit_text Limits the number of characters
    type_name Outputs the data type name
    Example: {{ data | type_name }}
    Output: dict
    to_int Converts to an integer
    Example: {{ data | to_int }}
    Output: 1
    to_float Converts to a floating-point number
    Example: {{ data | to_float }}
    Output: 1.234
    to_str Converts to a string
    Example: {{ data | to_str }}
    Output: 1.234
    to_json_dumps Converts to a JSON-serialized string
    Example: {{ data | to_json_dumps }}
    Output: {"key1":"value1","key2":"value2"}
    length Gets the data length
    Example: {{ data | length }}
    Output: 10

    Template Function Example

    For more details, see Get examples of each template function.

    Suppose the monitor's by is configured with region and host, and the template configured for the alert is as follows:

    Event name:

    Monitor {{ df_monitor_checker_name }} detected a fault in {{ df_dimension_tags | to_pretty_tags }}
    

    Event content:

    - Object: {{ df_dimension_tags | to_pretty_tags }}
    - Time: {{ date | to_datetime }}
    - Status: {{ df_status | to_status_human }}
    - Detection value: {{ (Result * 100) | to_round(2) }}
    

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

    Output event name:

    Monitor my-monitor detected a fault in region:hangzhou, host:web-001
    

    Output event content:

    - Detection object: region:hangzhou, host:web-001
    - Detection time: 2022-01-01 01:23:45
    - Fault severity: Error
    - Detection value: 9012.35
    

    Template Branches

    Templates also support branch syntax to render different content based on conditions.

    Template Branch Example

    The following example handles fatal alerts separately and outputs recovery information only when ok. Unlisted statuses display the original value to avoid mistakenly treating other events as normal:

    {% if df_status == 'fatal' %}
    Fatal issue. Handle it immediately!
    {% elif df_status == 'critical' %}
    Critical issue. Handle it immediately!
    {% elif df_status == 'error' %}
    Error issue. Handle it
    {% elif df_status == 'warning' %}
    Warning event. Pay attention
    {% elif df_status == 'nodata' %}
    No data. Check data reporting status
    {% elif df_status == 'info' %}
    Informational event. View as needed
    {% elif df_status == 'ok' %}
    Recovered to normal
    {% else %}
    Current event status: {{ df_status }}. View event details
    {% endif %}
    

    A more typical example is as follows:

    {% if  df_status != 'ok' %}
    > Severity: {{ df_status }}
    > Host: {{ host }}
    > Content: Elasticsearch JVM heap memory usage is {{ Result }}%
    > Recommendation: JVM garbage collection currently cannot keep up with JVM garbage generation. Check the business situation promptly
    
    {% else %}
    > Severity: {{df_status}}
    > Host: {{host}}
    > Content: Elasticsearch JVM heap memory alert has recovered
    
    {% endif %}
    

    Embedded DQL Query Function

    In some cases, template variables alone cannot meet rendering requirements. In this case, you can use the embedded DQL query function to perform additional data queries.

    The embedded DQL query function supports executing arbitrary DQL statements in the current workspace within the current detection time range. Usually, the first record returned by the query can be used as a template variable in the template, as follows:

    {% set dql_data = DQL("DQL statement to execute") %}
    
    Some field: {{ dql_data.some_field }}
    

    Embedded DQL Query Example

    The following embedded DQL statement queries data where the host field is "my_server" and assigns the first record to the dql_data variable:

    {% set dql_data = DQL("O::HOST:(host, host_ip, os, datakit_ver) { host = 'my_server' }") %}
    
    Host OS: {{ dql_data.os }}
    

    In the rest of the template, you can use {{ dql_data.os }} to output the specific field from the query result.

    Passing Parameters to Embedded DQL

    Sometimes, executing a DQL statement requires passing parameters. These parameters can be embedded directly in the DQL statement, and you can choose whether to add by filtering. However, the syntax is slightly different. Normally, variables are referenced using {{df_status}}. In a DQL statement, however, use the variable name directly without adding {{ }}; therefore, the final form is status.

    Suppose the monitor's by is configured with region and host, and the event content template is as follows:

    {% set dql_data = DQL("O::HOST:(host_ip, os) { region = ?, host = ? }", region, host) %}
    
    Host information:
    IP: {{ dql_data.host_ip }}
    OS: {{ dql_data.os }}
    

    Because the event contains only the region and host template variables to identify different data and does not contain more information such as IP address or operating system.

    Therefore, using embedded DQL, you can use region and host as DQL query parameters to obtain the corresponding data and use expressions such as {{ dql_data.host_ip }} to output related information.

    Embedded DQL Query Function Details

    The embedded DQL query function is called as follows:

    DQL(dql, param_1, param_2, ...)
    
    • The first parameter is a DQL statement and can contain the parameter placeholder ?
    • Subsequent parameters are parameter values or variables for the DQL statement

    When the parameter placeholder ? is replaced with a specific value, the system automatically escapes it.

    Suppose the value of the host variable is "my_server". Then the embedded DQL function and the final DQL statement executed are as follows:

    DQL("O::HOST:(host, host_ip, os, datakit_ver) { host = ? }",  host)
    
    O::HOST:(host, host_ip, os, datakit_ver) { host = 'my_server' }
    
    Warning
    • Embedded DQL queries should be placed at the beginning of the template.
    • The query result name (here, dql_data) follows the naming requirements of general programming languages. It can start with any English letter and contain only English letters, digits, and underscores. Using emoji is not recommended.
    • Do not give the query result name the same name as any existing template variable or template function; otherwise, unpredictable issues may occur.
    • If you use a function on a field in DQL, it is recommended to use AS to alias the field for later use (for example, O::HOST:( last(host) AS last_host )).
    • If a field name in DQL contains special characters, as with template variables, render it using {{ dql_data['host-name'] }} and {{ dql_data['@level'] }}.

    More DQL Documentation

    Feedback

    Is this page helpful?