Updated on 2025-08-21 GMT+08:00

Creating a Keyword Alarm Rule

Function

This API is used to create a keyword alarm. Currently, each account can create a maximum of 200 keyword alarms and SQL alarms.

Calling Method

For details, see Calling APIs.

URI

POST /v2/{project_id}/lts/alarms/keywords-alarm-rule

Table 1 Path Parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Definition

Project ID. It can be obtained by calling an API or from the console. For details, see Obtaining a Project ID.

Constraints

N/A

Range

N/A

Default Value

N/A

Request Parameters

Table 2 Request header parameters

Parameter

Mandatory

Type

Description

X-Auth-Token

Yes

String

Definition

User token obtained from IAM. For details about how to obtain it, see Obtaining a User Token.

Constraints

N/A

Range

N/A

Default Value

N/A

Content-Type

Yes

String

Definition

Message body format. Set this parameter to application/json;charset=utf8.

Constraints

N/A

Range

N/A

Default Value

N/A

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

keywords_alarm_rule_name

Yes

String

Definition

Keyword alarm rule name.

Constraints

You can modify the current rule name, but cannot modify the original rule name (defined during rule creation).

Range

  • Use only letters, digits, hyphens (-), and underscores (_). Do not start or end with a hyphen or underscore.

  • A maximum of 128 characters is allowed.

Default Value

N/A

keywords_alarm_rule_description

No

String

Definition

Brief description of a keyword alarm rule.

Constraints

N/A

Range

A maximum of 128 characters is allowed.

Default Value

N/A

keywords_requests

Yes

Array of KeywordsRequest objects

Definition

Keyword alarm rule information.

Constraints

N/A

frequency

Yes

Frequency object

Definition

Keyword alarm query frequency.

Constraints

N/A

keywords_alarm_level

Yes

String

Definition

Keyword alarm severity.

Constraints

N/A

Range

  • Info

  • Minor

  • Major

  • Critical

Default Value

N/A

domain_id

Yes

String

Definition

Account ID. For details about how to obtain it, see Obtaining an Account ID.

Constraints

N/A

Range

N/A

Default Value

N/A

trigger_condition_count

No

Integer

Definition

Alarm triggering condition: number of times the condition is met. It specifies the number of times a configured keyword must appear to trigger an alarm.

When this count is reached within a specified number of queries, a keyword alarm is triggered.

Constraints

  • trigger_condition_count and trigger_condition_frequency must be configured in conjunction to trigger a keyword alarm.

  • The number of queries (trigger_condition_frequency) must be greater than or equal to the number of times the condition must be met (trigger_condition_count).

Range

N/A

Default Value

N/A

trigger_condition_frequency

No

Integer

Definition

Alarm triggering condition: number of queries. It refers to the number of queries set in the advanced settings.

When the value of trigger_condition_count is reached within a specified number of queries, a keyword alarm is triggered.

Constraints

  • trigger_condition_count and trigger_condition_frequency must be configured in conjunction to trigger a keyword alarm.

  • The number of queries (trigger_condition_frequency) must be greater than or equal to the number of times the condition must be met (trigger_condition_count).

Range

Minimum value: 1

Maximum value: 10

Default Value

N/A

whether_recovery_policy

No

Boolean

Definition

Whether to configure an alarm restoration policy. If this policy is met, an alarm restoration notification is sent.

Constraints

N/A

Range

  • true: configures an alarm restoration policy.

  • false: does not configure an alarm restoration policy.

Default Value

false

recovery_policy

No

Integer

Definition

Number of consecutive queries in which the alarm's trigger condition must not be met.

If alarm restoration notification is enabled and the trigger condition has not been met for the specified number of last queries, an alarm restoration notification is sent.

Constraints

N/A

Range

  • Minimum value: 1

  • Maximum value: 10

Default Value

N/A

notification_frequency

Yes

Integer

Definition

Alarm notification frequency. The options are immediate, every 5 minutes, every 10 minutes, every 15 minutes, every 30 minutes, every 1 hour, every 3 hours, and every 6 hours.

Immediate indicates that a notification is sent once an alarm is generated. Every 10 minutes indicates that the minimum interval between two notifications is 10 minutes, preventing alarm storms.

Constraints

N/A

Range

  • 0*

  • 5

  • 10

  • 15

  • 30

  • 60

  • 180

  • 630

Default Value

N/A

alarm_action_rule_name

No

String

Definition

Alarm action rule name.

Constraints

N/A

Range

  • Use only letters, digits, hyphens (-), and underscores (_). Do not start or end with a hyphen or underscore.

  • A maximum of 128 characters is allowed.

Default Value

N/A

tags

No

Array of tagsRequestBody objects

Definition

Alarm tag information. A tag is a key-value pair. Each key is paired with its corresponding value.

Constraints

N/A

Table 4 KeywordsRequest

Parameter

Mandatory

Type

Description

log_stream_id

Yes

String

Definition

Log stream ID. For details about how to obtain it, see Obtaining Log Group and Log Stream IDs.

Constraints

N/A

Range

N/A

Default Value

N/A

log_stream_name

No

String

Definition

Log stream name.

If a log group contains more than one log stream, you can select multiple log streams when creating a keyword alarm rule.

Constraints

  • Use only letters, digits, hyphens (-), underscores (_), and periods (.). Do not start with a period or underscore or end with a period.

  • Enter 1 to 64 characters.

Range

N/A

Default Value

N/A

log_group_id

Yes

String

Definition

Log stream ID. For details about how to obtain it, see Obtaining Log Group and Log Stream IDs.

Constraints

N/A

Range

N/A

Default Value

N/A

log_group_name

No

String

Definition

Log group name.

Constraints

N/A

Range

N/A

Default Value

N/A

keywords

Yes

String

Definition

Keyword that can be found in logs. Exact and fuzzy matches are supported. Enter up to 1,024 characters. For details about how to set keyword search, see Using Search Syntax.

Constraints

N/A

Range

A maximum of 1,024 characters is allowed.

Default Value

N/A

condition

Yes

String

Definition

Trigger condition. When the condition is met, an alarm is triggered.

Constraints

N/A

Range

N/A

Default Value

N/A

number

Yes

Integer

Definition

Number of matching log events. When the number of log events that contain the configured keywords reaches the specified value, an alarm is triggered.

Constraints

N/A

Range

N/A

Default Value

N/A

search_time_range

Yes

Integer

Definition

Time range for querying the latest data when an alarm task is executed.

Constraints

  • When search_time_range_unit is set to minute, the maximum value is 60.

  • When search_time_range_unit is set to hour, the maximum value is 24.

Range

Minimum value: 1

Maximum value: 60

Default Value

1

search_time_range_unit

Yes

String

Definition

Unit of the alarm query time range.

Constraints

N/A

Range

  • minute

  • hour

Default Value

minute

Table 5 Frequency

Parameter

Mandatory

Type

Description

type

Yes

String

Definition

Query frequency type of alarms.

Constraints

N/A

Range

  • CRON: cron expression

  • HOURLY: every hour

  • DAILY: every day

  • WEEKLY: every week

  • FIXED_RATE: fixed interval

Default Value

N/A

cron_expr

No

String

Definition

Cron expression. This parameter is mandatory when type is set to CRON. Cron expressions use the 24-hour format and are precise down to the minute. Examples:

  • 0/9 * * * *: The query runs every 9 minutes, starting at the 0th minute of every hour.

  • 0 18 * * *: The query runs at 18:00:00 every day.

Constraints

N/A

Range

N/A

Default Value

N/A

hour_of_day

No

Integer

Definition

Every hour of every day. This parameter is mandatory when type is set to DAILY or HOURLY.

Constraints

N/A

Range

DAILY: 00:00 to 23:00

Default Value

N/A

day_of_week

No

Integer

Definition

Weekly. This parameter is mandatory when type is set to WEEKLY.

Constraints

N/A

Range

00:00 to 23:00 on Sunday to Saturday

Default Value

N/A

fixed_rate

No

Integer

Definition

Fixed interval. This parameter is mandatory when type is set to FIXED_RATE.

Constraints

N/A

Range

  • When fixed_rate_unit is set to minute, the maximum value is 60.

  • When fixed_rate_unit is set to hour, the maximum value is 24.

Default Value

N/A

fixed_rate_unit

No

String

Definition

Unit of the fixed interval.

Constraints

N/A

Range

  • minute

  • hour

Default Value

N/A

Table 6 tagsRequestBody

Parameter

Mandatory

Type

Description

key

Yes

String

Definition

Tag key.

Constraints

  • Each tag key must be unique.

  • A tag is a key-value pair. Each key is paired with its corresponding value.

Range

Each tag key can contain up to 128 characters, including only letters, digits, spaces, and special characters (_.:=+-@). Do not start or end with a space, nor start with sys.

Default Value

N/A

value

No

String

Definition

Tag value.

Constraints

A tag is a key-value pair. Each key is paired with its corresponding value.

Range

  • A tag value can contain letters, digits, spaces, and special characters (_.:=+-@).

  • A tag value can contain up to 255 characters.

Default Value

N/A

Response Parameters

Status code: 200

Table 7 Response body parameters

Parameter

Type

Description

keywords_alarm_rule_id

String

Definition

Keyword alarm rule ID.

Range

N/A

Status code: 400

Table 8 Response body parameters

Parameter

Type

Description

error_code

String

Definition

Error code. For details, see Error Codes.

Range

N/A

error_msg

String

Definition

Error message.

Range

N/A

Status code: 500

Table 9 Response body parameters

Parameter

Type

Description

error_code

String

Definition

Error code. For details, see Error Codes.

Range

N/A

error_msg

String

Definition

Error message.

Range

N/A

Example Requests

Create a keyword alarm rule.

POST https://{endpoint}/v2/{project_id}/lts/alarms/keywords-alarm-rule 

{
  "keywords_alarm_rule_name" : "huawei",
  "keywords_alarm_rule_description" : "huawei",
  "keywords_requests" : [ {
    "log_stream_id" : "1",
    "log_group_id" : "1",
    "keywords" : "huawei",
    "condition" : ">",
    "number" : "100",
    "search_time_range" : 10,
    "search_time_range_unit" : "minute"
  } ],
  "frequency" : {
    "type" : "FIXED_RATE",
    "cron_expr" : "",
    "hour_of_day" : 0,
    "day_of_week" : 0,
    "fixed_rate" : 10,
    "fixed_rate_unit" : "minute"
  },
  "keywords_alarm_level" : "Critical",
  "domain_id" : "",
  "notification_frequency" : 5,
  "alarm_action_rule_name" : ""
}

Example Responses

Status code: 200

The request is successful.

{
  "keywords_alarm_rule_id" : ""
}

Status code: 400

Invalid request. Modify the request based on the description in error_msg before a retry.

{
  "error_code" : "LTS.2005",
  "error_msg" : "Alarm rule params validator error."
}

Status code: 500

The server has received the request but encountered an internal error.

{
  "error_code" : "LTS.2001",
  "error_msg" : "Failed to create alarm rule."
}

SDK Sample Code

The SDK sample code is as follows.

Create a keyword alarm rule.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.huaweicloud.sdk.test;

import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.lts.v2.region.LtsRegion;
import com.huaweicloud.sdk.lts.v2.*;
import com.huaweicloud.sdk.lts.v2.model.*;

import java.util.List;
import java.util.ArrayList;

public class CreateKeywordsAlarmRuleSolution {

    public static void main(String[] args) {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        String ak = System.getenv("CLOUD_SDK_AK");
        String sk = System.getenv("CLOUD_SDK_SK");
        String projectId = "{project_id}";

        ICredential auth = new BasicCredentials()
                .withProjectId(projectId)
                .withAk(ak)
                .withSk(sk);

        LtsClient client = LtsClient.newBuilder()
                .withCredential(auth)
                .withRegion(LtsRegion.valueOf("<YOUR REGION>"))
                .build();
        CreateKeywordsAlarmRuleRequest request = new CreateKeywordsAlarmRuleRequest();
        CreateKeywordsAlarmRuleRequestBody body = new CreateKeywordsAlarmRuleRequestBody();
        Frequency frequencybody = new Frequency();
        frequencybody.withType(Frequency.TypeEnum.fromValue("FIXED_RATE"))
            .withCronExpr("")
            .withHourOfDay(0)
            .withDayOfWeek(0)
            .withFixedRate(10)
            .withFixedRateUnit(Frequency.FixedRateUnitEnum.fromValue("minute"));
        List<KeywordsRequest> listbodyKeywordsRequests = new ArrayList<>();
        listbodyKeywordsRequests.add(
            new KeywordsRequest()
                .withLogStreamId("1")
                .withLogGroupId("1")
                .withKeywords("huawei")
                .withCondition(KeywordsRequest.ConditionEnum.fromValue(">"))
                .withNumber(100)
                .withSearchTimeRange(10)
                .withSearchTimeRangeUnit(KeywordsRequest.SearchTimeRangeUnitEnum.fromValue("minute"))
        );
        body.withAlarmActionRuleName("");
        body.withNotificationFrequency(CreateKeywordsAlarmRuleRequestBody.NotificationFrequencyEnum.NUMBER_5);
        body.withDomainId("");
        body.withKeywordsAlarmLevel(CreateKeywordsAlarmRuleRequestBody.KeywordsAlarmLevelEnum.fromValue("Critical"));
        body.withFrequency(frequencybody);
        body.withKeywordsRequests(listbodyKeywordsRequests);
        body.withKeywordsAlarmRuleDescription("huawei");
        body.withKeywordsAlarmRuleName("huawei");
        request.withBody(body);
        try {
            CreateKeywordsAlarmRuleResponse response = client.createKeywordsAlarmRule(request);
            System.out.println(response.toString());
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getRequestId());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
        }
    }
}

Create a keyword alarm rule.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# coding: utf-8

import os
from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdklts.v2.region.lts_region import LtsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdklts.v2 import *

if __name__ == "__main__":
    # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
    # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
    ak = os.environ["CLOUD_SDK_AK"]
    sk = os.environ["CLOUD_SDK_SK"]
    projectId = "{project_id}"

    credentials = BasicCredentials(ak, sk, projectId)

    client = LtsClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(LtsRegion.value_of("<YOUR REGION>")) \
        .build()

    try:
        request = CreateKeywordsAlarmRuleRequest()
        frequencybody = Frequency(
            type="FIXED_RATE",
            cron_expr="",
            hour_of_day=0,
            day_of_week=0,
            fixed_rate=10,
            fixed_rate_unit="minute"
        )
        listKeywordsRequestsbody = [
            KeywordsRequest(
                log_stream_id="1",
                log_group_id="1",
                keywords="huawei",
                condition=">",
                number=100,
                search_time_range=10,
                search_time_range_unit="minute"
            )
        ]
        request.body = CreateKeywordsAlarmRuleRequestBody(
            alarm_action_rule_name="",
            notification_frequency=5,
            domain_id="",
            keywords_alarm_level="Critical",
            frequency=frequencybody,
            keywords_requests=listKeywordsRequestsbody,
            keywords_alarm_rule_description="huawei",
            keywords_alarm_rule_name="huawei"
        )
        response = client.create_keywords_alarm_rule(request)
        print(response)
    except exceptions.ClientRequestException as e:
        print(e.status_code)
        print(e.request_id)
        print(e.error_code)
        print(e.error_msg)

Create a keyword alarm rule.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main

import (
	"fmt"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
    lts "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2/model"
    region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2/region"
)

func main() {
    // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
    // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
    ak := os.Getenv("CLOUD_SDK_AK")
    sk := os.Getenv("CLOUD_SDK_SK")
    projectId := "{project_id}"

    auth := basic.NewCredentialsBuilder().
        WithAk(ak).
        WithSk(sk).
        WithProjectId(projectId).
        Build()

    client := lts.NewLtsClient(
        lts.LtsClientBuilder().
            WithRegion(region.ValueOf("<YOUR REGION>")).
            WithCredential(auth).
            Build())

    request := &model.CreateKeywordsAlarmRuleRequest{}
	cronExprFrequency:= ""
	hourOfDayFrequency:= int32(0)
	dayOfWeekFrequency:= int32(0)
	fixedRateFrequency:= int32(10)
	fixedRateUnitFrequency:= model.GetFrequencyFixedRateUnitEnum().MINUTE
	frequencybody := &model.Frequency{
		Type: model.GetFrequencyTypeEnum().FIXED_RATE,
		CronExpr: &cronExprFrequency,
		HourOfDay: &hourOfDayFrequency,
		DayOfWeek: &dayOfWeekFrequency,
		FixedRate: &fixedRateFrequency,
		FixedRateUnit: &fixedRateUnitFrequency,
	}
	var listKeywordsRequestsbody = []model.KeywordsRequest{
        {
            LogStreamId: "1",
            LogGroupId: "1",
            Keywords: "huawei",
            Condition: model.GetKeywordsRequestConditionEnum().GREATER_THAN,
            Number: int32(100),
            SearchTimeRange: int32(10),
            SearchTimeRangeUnit: model.GetKeywordsRequestSearchTimeRangeUnitEnum().MINUTE,
        },
    }
	alarmActionRuleNameCreateKeywordsAlarmRuleRequestBody:= ""
	keywordsAlarmRuleDescriptionCreateKeywordsAlarmRuleRequestBody:= "huawei"
	request.Body = &model.CreateKeywordsAlarmRuleRequestBody{
		AlarmActionRuleName: &alarmActionRuleNameCreateKeywordsAlarmRuleRequestBody,
		NotificationFrequency: model.GetCreateKeywordsAlarmRuleRequestBodyNotificationFrequencyEnum().E_5,
		DomainId: "",
		KeywordsAlarmLevel: model.GetCreateKeywordsAlarmRuleRequestBodyKeywordsAlarmLevelEnum().CRITICAL,
		Frequency: frequencybody,
		KeywordsRequests: listKeywordsRequestsbody,
		KeywordsAlarmRuleDescription: &keywordsAlarmRuleDescriptionCreateKeywordsAlarmRuleRequestBody,
		KeywordsAlarmRuleName: "huawei",
	}
	response, err := client.CreateKeywordsAlarmRule(request)
	if err == nil {
        fmt.Printf("%+v\n", response)
    } else {
        fmt.Println(err)
    }
}

For SDK sample code of more programming languages, see the Sample Code tab in API Explorer. SDK sample code can be automatically generated.

Status Codes

Status Code

Description

200

The request is successful.

400

Invalid request. Modify the request based on the description in error_msg before a retry.

500

The server has received the request but encountered an internal error.

Error Codes

See Error Codes.