tencentcloud-cls-alarm

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Tencent Cloud CLS — Alarm Management

腾讯云CLS — 告警管理

CRUD on CLS alarm policies, notice groups, mute shields, and the alarm execution log.
Setup: See tencentcloud authentication. Defaults to
TENCENTCLOUD_REGION
from env; CLS alarms live per-region.
Companion skill:
tencentcloud-cls
for log content search.
对CLS告警策略、通知组、静音屏蔽规则及告警执行日志执行增删改查(CRUD)操作。
配置说明: 请查看腾讯云认证。默认使用环境变量中的
TENCENTCLOUD_REGION
;CLS告警为区域级资源。
配套技能: 使用
tencentcloud-cls
技能进行日志内容搜索。

CLI (preferred)

CLI(推荐方式)

The skill ships
scripts/cls_alarm.py
— wraps every alarm / notice / shield operation as a subcommand.
bash
A=$SKILL_DIR/scripts/cls_alarm.py

python3 $A alarms                              # list policies
python3 $A alarm <alarm-id>                    # full detail
python3 $A alarm-disable <alarm-id>            # quick mute (Status=false)
python3 $A alarm-enable  <alarm-id>
python3 $A alarm-create --json /tmp/alarm.json --dry-run
python3 $A alarm-modify <alarm-id> --condition '$1.cnt > 20'
python3 $A alarm-delete <alarm-id> --yes       # destructive

python3 $A notices                             # notice groups
python3 $A notice <notice-id>

python3 $A shields                             # mute rules
python3 $A shield-create --notice-id <notice-id> --start $(date +%s) --end $(date -v+2H +%s) --type 1 --reason "deploy"

python3 $A alarm-log --time 6h                 # firing history
For the rare schema field the CLI doesn't surface, fall through to the raw SDK examples below.
该技能提供了
scripts/cls_alarm.py
脚本——将所有告警/通知/屏蔽操作封装为子命令。
bash
A=$SKILL_DIR/scripts/cls_alarm.py

python3 $A alarms                              # 列出告警策略
python3 $A alarm <alarm-id>                    # 查看完整详情
python3 $A alarm-disable <alarm-id>            # 快速静音(Status=false)
python3 $A alarm-enable  <alarm-id>
python3 $A alarm-create --json /tmp/alarm.json --dry-run
python3 $A alarm-modify <alarm-id> --condition '$1.cnt > 20'
python3 $A alarm-delete <alarm-id> --yes       # 破坏性操作

python3 $A notices                             # 列出通知组
python3 $A notice <notice-id>

python3 $A shields                             # 列出静音规则
python3 $A shield-create --notice-id <notice-id> --start $(date +%s) --end $(date -v+2H +%s) --type 1 --reason "deploy"

python3 $A alarm-log --time 6h                 # 查看告警触发历史
若CLI未覆盖少数Schema字段,可使用下方的原生SDK示例。

When to Use

使用场景

  • Inspect existing alarm policies (filter by name, enabled flag)
  • Create a new log-based alarm: CQL/SQL query → trigger condition → notice group
  • Modify thresholds, query, period, recipients
  • Quick enable / disable to mute during incidents
  • Manage notice groups (recipients: users, groups, webhooks, with escalation)
  • Time-bounded shield rules to mute during deploys
  • Pull the alarm execution log to see which alarms fired and when
  • 查看现有告警策略(按名称、启用状态过滤)
  • 创建基于日志的新告警:CQL/SQL查询 → 触发条件 → 通知组
  • 修改阈值、查询语句、周期、接收人
  • 快速启用/禁用告警,在事件期间静音
  • 管理通知组(接收人:用户、用户组、Webhook,支持升级机制)
  • 设置限时屏蔽规则,在部署期间静音告警
  • 拉取告警执行日志,查看哪些告警触发及触发时间

Dependencies

依赖

bash
pip install tencentcloud-sdk-python
bash
pip install tencentcloud-sdk-python

Quick start

快速开始

python
import os
import json
from tencentcloud.common import credential
from tencentcloud.cls.v20201016 import cls_client, models

cred = credential.EnvironmentVariableCredential().get_credential()
client = cls_client.ClsClient(cred, os.environ["TENCENTCLOUD_REGION"])
python
import os
import json
from tencentcloud.common import credential
from tencentcloud.cls.v20201016 import cls_client, models

cred = credential.EnvironmentVariableCredential().get_credential()
client = cls_client.ClsClient(cred, os.environ["TENCENTCLOUD_REGION"])

Key concepts

核心概念

ObjectAPI methodsWhat it is
Alarm policy
DescribeAlarms
/
CreateAlarm
/
ModifyAlarm
/
DeleteAlarm
Query against one or more topics + condition + notice groups
Notice group
DescribeAlarmNotices
/
CreateAlarmNotice
/ …
Recipients (users / groups / webhooks) + escalation
Shield
DescribeAlarmShields
/
CreateAlarmShield
/ …
Time-bounded mute scoped to a notice group
Alarm log
GetAlarmLog
Firing history
对象API方法说明
Alarm policy
DescribeAlarms
/
CreateAlarm
/
ModifyAlarm
/
DeleteAlarm
针对一个或多个日志主题的查询 + 触发条件 + 通知组
Notice group
DescribeAlarmNotices
/
CreateAlarmNotice
/ …
接收人(用户/用户组/Webhook) + 升级机制
Shield
DescribeAlarmShields
/
CreateAlarmShield
/ …
针对特定通知组的限时静音规则
Alarm log
GetAlarmLog
告警触发历史

Workflows

工作流

List alarm policies

列出告警策略

python
req = models.DescribeAlarmsRequest()
req.Limit = 100
python
req = models.DescribeAlarmsRequest()
req.Limit = 100

Optional filters: req.Filters = [{"Key": "name", "Values": ["DeepSeek"]}]

可选过滤条件: req.Filters = [{"Key": "name", "Values": ["DeepSeek"]}]

resp = client.DescribeAlarms(req) for a in resp.Alarms: print(a.AlarmId, a.Name, "Enable=", a.Enable, "Status=", a.Status)
undefined
resp = client.DescribeAlarms(req) for a in resp.Alarms: print(a.AlarmId, a.Name, "Enable=", a.Enable, "Status=", a.Status)
undefined

Get a single alarm policy in full

获取单个告警策略的完整信息

python
req = models.DescribeAlarmsRequest()
req.Filters = [{"Key": "alarmId", "Values": ["<alarm-id>"]}]
resp = client.DescribeAlarms(req)
print(json.dumps(resp.Alarms[0]._serialize(), indent=2, ensure_ascii=False))
python
req = models.DescribeAlarmsRequest()
req.Filters = [{"Key": "alarmId", "Values": ["<alarm-id>"]}]
resp = client.DescribeAlarms(req)
print(json.dumps(resp.Alarms[0]._serialize(), indent=2, ensure_ascii=False))

Create an alarm

创建告警

python
req = models.CreateAlarmRequest()
req.Name = "OpenAI 5xx burst"
req.AlarmTargets = [{
    "TopicId": "<trace-topic-id>",
    "Query": "* | select count(*) as cnt where status_code >= 500",
    "Number": 1,
    "StartTimeOffset": -5,
    "EndTimeOffset": 0,
    "SyntaxRule": 1,             # 1 = CQL, 0 = Lucene
}]
req.MonitorTime = {"Type": "Period", "Time": 1}
req.Condition = "$1.cnt > 10"
req.AlarmPeriod = 5              # evaluate every 5 minutes
req.TriggerCount = 1             # fire after 1 consecutive match
req.AlarmLevel = 2               # 0=Notice, 1=Warning, 2=Critical
req.AlarmNoticeIds = ["<notice-id-a>", "<notice-id-b>"]
req.MonitorObjectType = 0
req.Enable = True

resp = client.CreateAlarm(req)
print("Created", resp.AlarmId)
python
req = models.CreateAlarmRequest()
req.Name = "OpenAI 5xx突发告警"
req.AlarmTargets = [{
    "TopicId": "<trace-topic-id>",
    "Query": "* | select count(*) as cnt where status_code >= 500",
    "Number": 1,
    "StartTimeOffset": -5,
    "EndTimeOffset": 0,
    "SyntaxRule": 1,             # 1 = CQL, 0 = Lucene
}]
req.MonitorTime = {"Type": "Period", "Time": 1}
req.Condition = "$1.cnt > 10"
req.AlarmPeriod = 5              # 每5分钟评估一次
req.TriggerCount = 1             # 连续匹配1次后触发告警
req.AlarmLevel = 2               # 0=通知, 1=警告, 2=严重
req.AlarmNoticeIds = ["<notice-id-a>", "<notice-id-b>"]
req.MonitorObjectType = 0
req.Enable = True

resp = client.CreateAlarm(req)
print("已创建告警", resp.AlarmId)

Quick enable / disable

快速启用/禁用告警

python
req = models.ModifyAlarmRequest()
req.AlarmId = "<alarm-id>"
req.Status = False               # mute (Status — runtime), keep Enable=True
client.ModifyAlarm(req)
Enable
vs
Status
are different fields.
Enable=False
archives the alarm definition;
Status=False
is the everyday on/off switch you want for muting.
python
req = models.ModifyAlarmRequest()
req.AlarmId = "<alarm-id>"
req.Status = False               # 静音(Status为运行时状态),保持Enable=True
client.ModifyAlarm(req)
Enable
Status
的区别
Enable=False
会归档告警定义;
Status=False
是日常使用的启停开关,用于静音告警。

Modify thresholds without rewriting the whole payload

修改阈值(无需重写完整请求体)

python
req = models.ModifyAlarmRequest()
req.AlarmId = "<alarm-id>"
req.Condition = "$1.cnt > 20"
req.AlarmPeriod = 10
client.ModifyAlarm(req)
python
req = models.ModifyAlarmRequest()
req.AlarmId = "<alarm-id>"
req.Condition = "$1.cnt > 20"
req.AlarmPeriod = 10
client.ModifyAlarm(req)

Delete (destructive)

删除告警(破坏性操作)

python
undefined
python
undefined

Confirm with the user first — there's no undo.

请先确认用户意愿——此操作不可撤销。

req = models.DeleteAlarmRequest() req.AlarmId = "<alarm-id>" client.DeleteAlarm(req)
undefined
req = models.DeleteAlarmRequest() req.AlarmId = "<alarm-id>" client.DeleteAlarm(req)
undefined

Manage notice groups

管理通知组

python
undefined
python
undefined

List

列出通知组

req = models.DescribeAlarmNoticesRequest() req.Limit = 100 for n in client.DescribeAlarmNotices(req).AlarmNotices: print(n.AlarmNoticeId, n.Name, n.Type)
req = models.DescribeAlarmNoticesRequest() req.Limit = 100 for n in client.DescribeAlarmNotices(req).AlarmNotices: print(n.AlarmNoticeId, n.Name, n.Type)

Create

创建通知组

req = models.CreateAlarmNoticeRequest() req.Name = "Ops on-call" req.Type = "Trigger" # Trigger | Recovery | All req.NoticeReceivers = [{ "ReceiverType": "Uin", "ReceiverIds": [123456], "ReceiverChannels": ["Email", "Sms"], "StartTime": "00:00:00", "EndTime": "23:59:59", }] req.WebCallbacks = [{ "Url": "https://hooks.example.com/cls", "CallbackType": "WeCom", "Method": "POST", }] resp = client.CreateAlarmNotice(req)
undefined
req = models.CreateAlarmNoticeRequest() req.Name = "运维值班组" req.Type = "Trigger" # Trigger | Recovery | All req.NoticeReceivers = [{ "ReceiverType": "Uin", "ReceiverIds": [123456], "ReceiverChannels": ["Email", "Sms"], "StartTime": "00:00:00", "EndTime": "23:59:59", }] req.WebCallbacks = [{ "Url": "https://hooks.example.com/cls", "CallbackType": "WeCom", "Method": "POST", }] resp = client.CreateAlarmNotice(req)
undefined

Time-bounded shield (mute during deploy)

限时屏蔽规则(部署期间静音)

python
import time
req = models.CreateAlarmShieldRequest()
req.AlarmNoticeId = "<notice-id>"
req.StartTime = int(time.time())
req.EndTime = int(time.time()) + 7200       # 2 hours
req.Type = 1                                # 1 = full shield, 2 = partial
req.Reason = "Deploy <git-sha>"
client.CreateAlarmShield(req)
python
import time
req = models.CreateAlarmShieldRequest()
req.AlarmNoticeId = "<notice-id>"
req.StartTime = int(time.time())
req.EndTime = int(time.time()) + 7200       # 2小时
req.Type = 1                                # 1 = 完全屏蔽, 2 = 部分屏蔽
req.Reason = "Deploy <git-sha>"
client.CreateAlarmShield(req)

Inspect alarm firing history

查看告警触发历史

python
req = models.GetAlarmLogRequest()
req.From = int((time.time() - 86400) * 1000)
req.To = int(time.time() * 1000)
req.Query = 'alarm_name:"OpenAI*"'
req.Limit = 100
resp = client.GetAlarmLog(req)
for line in resp.Results:
    print(line.Time, line.LogJson)
python
req = models.GetAlarmLogRequest()
req.From = int((time.time() - 86400) * 1000)
req.To = int(time.time() * 1000)
req.Query = 'alarm_name:"OpenAI*"'
req.Limit = 100
resp = client.GetAlarmLog(req)
for line in resp.Results:
    print(line.Time, line.LogJson)

Cloning an alarm

克隆告警

The fastest way to create a similar alarm is to read the existing one, strip read-only fields, tweak, and re-create:
python
import json
existing = client.DescribeAlarms(models.DescribeAlarmsRequest(Filters=[{"Key": "alarmId", "Values": ["<src-id>"]}])).Alarms[0]
payload = json.loads(json.dumps(existing._serialize()))      # deep clone
for k in ("AlarmId", "CreateTime", "UpdateTime"):
    payload.pop(k, None)
payload["Name"] = "OpenAI 5xx burst v2"
创建相似告警的最快方式是读取现有告警配置,移除只读字段,调整后重新创建:
python
import json
existing = client.DescribeAlarms(models.DescribeAlarmsRequest(Filters=[{"Key": "alarmId", "Values": ["<src-id>"]}])).Alarms[0]
payload = json.loads(json.dumps(existing._serialize()))      # 深度克隆
for k in ("AlarmId", "CreateTime", "UpdateTime"):
    payload.pop(k, None)
payload["Name"] = "OpenAI 5xx突发告警 v2"

...edit other fields...

...编辑其他字段...

req = models.CreateAlarmRequest() req.from_json_string(json.dumps(payload)) print(client.CreateAlarm(req).AlarmId)
undefined
req = models.CreateAlarmRequest() req.from_json_string(json.dumps(payload)) print(client.CreateAlarm(req).AlarmId)
undefined

Important reminders

重要提醒

  • Always preview the payload (
    json.dumps(req._serialize(), indent=2)
    ) before
    CreateAlarm
    /
    ModifyAlarm
    — schema is strict and errors are unhelpful.
  • Destructive ops (
    DeleteAlarm
    ,
    DeleteAlarmNotice
    ,
    DeleteAlarmShield
    ) need explicit user confirmation in chat before running.
  • Enable
    (archived?) vs
    Status
    (currently on?) are different fields. Use
    Status
    for everyday muting.
  • Shield rules are scoped to a single
    AlarmNoticeId
    . Iterate over all notice IDs to list all shields globally.
  • Default region is
    ap-hongkong
    ; pass another region via
    cls_client.ClsClient(cred, "ap-singapore")
    if needed.
  • 创建/修改告警前请务必预览请求体
    json.dumps(req._serialize(), indent=2)
    )——Schema要求严格,错误提示不够友好。
  • 破坏性操作(
    DeleteAlarm
    ,
    DeleteAlarmNotice
    ,
    DeleteAlarmShield
    )需在聊天中获得用户明确确认后再执行。
  • Enable
    (是否归档?)与
    Status
    (当前是否启用?)是不同的字段。日常静音请使用
    Status
  • 屏蔽规则仅针对单个
    AlarmNoticeId
    生效。如需查看全局所有屏蔽规则,请遍历所有通知组ID。
  • 默认区域为
    ap-hongkong
    ;如需使用其他区域,请通过
    cls_client.ClsClient(cred, "ap-singapore")
    指定。

Console links

控制台链接