全部產品
Search
文件中心

Cloud Monitor:Live-Debug ServiceTask API 參考

更新時間:Aug 04, 2026

通過阿里雲 CMS OpenAPI(ServiceTaskController,API 版本 2024-03-30)管理 Live-Debug 探針任務,在不重啟應用的情況下動態下發代碼探針(LOG / SNAPSHOT / METRIC / SPAN / SPAN_TAG),即時採集函數入參、傳回值、自訂指標等運行時資料,並通過 SLS 查詢採集結果。本文僅覆蓋 Python 應用(Probe 探針任務)。

介面一覽

操作

HTTP

Path

CLI 命令

建立任務

POST

/serviceTask/{workspace}/{serviceId}/task

aliyun cms2 apm service-task create

列舉任務

GET

/serviceTask/{workspace}/{serviceId}/tasks

aliyun cms2 apm service-task list

查詢單個任務

GET

/serviceTask/{workspace}/{serviceId}/task/{taskId}

aliyun cms2 apm service-task get

刪除任務

DELETE

/serviceTask/{workspace}/{serviceId}/task/{taskId}

aliyun cms2 apm service-task delete

查詢採集結果

SLS get-logs-v2

(非 CMS)

aliyun sls get-logs-v2

路徑參數(Path)

參數

類型

必填

說明

workspace

string

ARMS 工作空間 ID,如 default-cms-xxx-cn-hangzhou

serviceId

string

應用/服務 ID,如 ggxw4lnjuz@f2fd3a6265a254a052afb

taskId

string

Get/Delete 必填

建立介面返回的任務 ID

公用 CLI 參數

參數

說明

預設

--region

接入地區;CMS 與 SLS 命令都建議顯式傳入,避免依賴 CLI 預設地區

阿里雲 CLI 配置的預設地區

--endpoint

直接指定 CMS endpoint,覆蓋按 region 的推導

cms.${regionId}.aliyuncs.com

-o json

縮排 JSON 輸出(預設 text 為單行緊湊 JSON)

text

建立任務(CreateServiceTask)

請求

POST /serviceTask/{workspace}/{serviceId}/task
Content-Type: application/json

Body 參數

參數

類型

必填

說明

type

string

任務類型,即 taskType,見下文"任務類型枚舉"

ip

string

目標執行個體 IP;匹配全部執行個體填 *

taskConfig

string(JSON 文本)

扁平的單命令/單探針配置;服務端按字串儲存。CLI 的 --task-config 接收原始 JSON 對象並自動序列化為字串

調用樣本:

aliyun cms2 apm service-task create \
  --workspace <workspace> --service-id <serviceId> \
  --type <taskType> --ip '<targetIp>' \
  --task-config '<taskConfigJson>' \
  --region <regionId> -o json
  • 匹配全部執行個體時 --ip*

  • --task-config 直接傳原始 JSON 對象,無需手動二次轉義。

響應(CLI 輸出)

{
  "success": true,
  "data": {
    "requestId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "taskId": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"
  }
}

欄位

說明

data.requestId

本次請求 ID

data.taskId

任務 ID;查詢 SLS 結果、Get、Delete 均使用該值

Body 樣本(CLI 拼裝後的 HTTP 形態)

{
  "type": "live_debug_log_probe",
  "ip": "*",
  "taskConfig": "{\"probeType\":\"LOG\",\"language\":\"python\",\"target\":{\"typeName\":\"app.service.order\",\"methodName\":\"OrderService.create_order\",\"location\":\"exit\",\"instanceIds\":[\"*\"]},\"action\":{\"type\":\"LOG\",\"template\":\"id={order_id}\"},\"ttl\":\"30m\",\"captureCount\":100}"
}

HTTP Body 裡 taskConfig 是轉義後的 JSON 字串;向 CLI --task-config 傳參時傳未轉義的對象 JSON 即可,轉義由 CLI 完成。

列舉任務(ListServiceTask)

請求

GET /serviceTask/{workspace}/{serviceId}/tasks?type={taskType}&maxResults={n}

Query 參數

參數

類型

必填

說明

type

string

精確匹配的任務類型,如 live_debug_log_probe

maxResults

int

返回條數上限,預設 100,API 上限 100

響應欄位

CLI 輸出 data.serviceTasks[] 數組,每項常見欄位:

欄位

說明

taskId

任務 ID

type

任務類型

serviceId

服務 ID

ip

建立時指定的 IP / *

createTime

建立時間

updateTime

更新時間

taskConfig

任務配置(扁平探針對象)

調用樣本:

aliyun cms2 apm service-task list \
  --workspace <workspace> --service-id <serviceId> \
  --type <taskType> --max-results 100 \
  --region <regionId> -o json

查詢單個任務(GetServiceTask)

請求

GET /serviceTask/{workspace}/{serviceId}/task/{taskId}?type={taskType}

Query 參數

參數

類型

必填

說明

type

string

必須與任務實際類型一致

響應

CLI 輸出 data.serviceTask 對象,欄位同 List 單項。

調用樣本:

aliyun cms2 apm service-task get \
  --workspace <workspace> --service-id <serviceId> \
  --task-id <taskId> --type <taskType> \
  --region <regionId> -o json

刪除任務(DeleteServiceTask)

請求

DELETE /serviceTask/{workspace}/{serviceId}/task/{taskId}?type={taskType}

Query 參數

參數

類型

必填

說明

type

string

必須與任務實際類型一致

刪除後服務端移除任務並 syncToConfigServer,Agent 側對應探針隨之失效。這是停用已下發探針的正確方式

調用樣本:

aliyun cms2 apm service-task delete \
  --workspace <workspace> --service-id <serviceId> \
  --task-id <taskId> --type <taskType> \
  --region <regionId> -o json

批量清空某服務下全部 Probe(List 按 type 精確過濾,需對五種 probe type 逐個 list + delete):

WS=<workspace>; SVC=<serviceId>; REGION=<regionId>
for t in live_debug_log_probe live_debug_snapshot_probe \
         live_debug_metric_probe live_debug_span_probe live_debug_span_tag_probe; do
  aliyun cms2 apm service-task list \
    --workspace "$WS" --service-id "$SVC" --type "$t" --region "$REGION" -o json |

  python3 -c 'import sys,json; [print(t["taskId"]) for t in (json.load(sys.stdin)["data"].get("serviceTasks") or [])]' |

  while read -r id; do
    aliyun cms2 apm service-task delete \
      --workspace "$WS" --service-id "$SVC" \
      --task-id "$id" --type "$t" --region "$REGION" -o json
  done
done

查詢採集結果(SLS)

採集狀態與結果寫入 SLS,不通過 CMS Get 介面返回業務資料。

調用樣本(查詢最近 10 分鐘,<taskId> 為建立返回的任務 ID):

FROM=$(( $(date +%s) - 600 )); TO=$(date +%s)

# 任務狀態(安裝狀態、funnel 指標)
aliyun sls get-logs-v2 --region <regionId> --accept-encoding gzip \
  --project <slsProject> --logstore logstore-apm-logs \
  --from "$FROM" --to "$TO" \
  --query "* and \"<taskId>\" | SELECT content FROM log WHERE json_extract_scalar(attributes, '\$[\"livedebug.report_type\"]') = 'status'"

# 採集結果(實際捕獲資料)
aliyun sls get-logs-v2 --region <regionId> --accept-encoding gzip \
  --project <slsProject> --logstore logstore-apm-logs \
  --from "$FROM" --to "$TO" \
  --query "* and \"<taskId>\" | SELECT content FROM log WHERE json_extract_scalar(attributes, '\$[\"livedebug.report_type\"]') != 'status'"

參數

必填

說明

--project

應用接入的 SLS Project(如 proj-xtrace-...-cn-hangzhou

--logstore

預設 logstore-apm-logs

--from / --to

Unix 秒級時間戳記查詢區間

--region

與 Project 同地區,需顯式傳入

兩類查詢:

類型

過濾條件

含義

Task Status

livedebug.report_type = 'status'

安裝狀態、funnel 指標

Capture Results

livedebug.report_type != 'status'

實際採集資料

SLS Project 按地區隔離。--region 錯誤會報 ProjectNotExist

任務類型枚舉(taskType/type)

Probe(代碼增強)

taskType

探針類型

live_debug_log_probe

LOG

live_debug_snapshot_probe

SNAPSHOT

live_debug_metric_probe

METRIC

live_debug_span_probe

SPAN

live_debug_span_tag_probe

SPAN_TAG

命名規則:live_debug_ + 探針語義小寫 + _probe。五種探針 Python 均支援。

Probe taskConfig 通用結構

建立時傳入的扁平對象(--task-config 入參形態):

{
  "probeType": "LOG|SNAPSHOT|METRIC|SPAN|SPAN_TAG",
  "language": "python",
  "target": { },
  "action": { },
  "trigger": { },
  "rateLimit": { },
  "ttl": "1h",
  "captureCount": 100,
  "enabled": true
}

頂層欄位

欄位

類型

必填

說明

probeType

string

LOG / SNAPSHOT / METRIC / SPAN / SPAN_TAG

language

string

固定 python

target

object

定位目標方法/行

action

object

探針動作;結構隨 probeType 變化

trigger

object

觸發條件

rateLimit

object

速率控制

ttl

string

captureCount 至少其一

存活時間長度。支援 30s/5m/2h/1d 或純秒數,不要用 ms

captureCount

int

ttl 至少其一

最大採集次數;與 ttl 任一先滿足即終止

enabled

boolean

建立時通常為 true不能靠建立 false 禁用已有探針

target — 定位目標

欄位

類型

必填

說明

typeName

string

函數級建議必填

模組名(sys.modules key),如 app.service.order;主模組填 __main__

methodName

string

函數級建議必填

函數 __qualname__,類方法寫 OrderService.create_order,普通函數直接寫函數名

sourceFile

string

否(行級建議填)

源碼檔案名稱或路徑尾碼

location

string

Hook 點:enter / exit / exception / line:N;預設 exitSPAN 只支援函數級,不能用 line

instanceIds

string[]

強烈建議必填

生效執行個體 ID 列表,必須放在 target 內(不要放 taskConfig 頂層);["*"] 表示全部。為空白時探針不生效

instanceIps

string[]

生效 IP 列表;與 instanceIds 為 AND

行級探針可主要依賴 sourceFile + location:"line:N"

trigger — 觸發條件(可選)

欄位

類型

預設

說明

condition

string

-

為真時才採集

callerPattern

string

-

調用方過濾(Python 情境較少使用)

條件樣本:amount > 10000@return is None or amount > 10000

運算式規則:

  • 直接使用參數名/局部變數/模組全域變數。

  • exit / exception 可用 @return@duration(毫秒)、@exception

  • 不要使用 OGNL、args[0]returnValuedurationMs

  • 若條件引用 @return / @exception,探針 location 必須是 exitexception

rateLimit — 速率控制(可選)

欄位

類型

預設

說明

maxExecutionsPerSecond

int

按探針類型(見下)

令牌桶每秒最多執行次數

samplingProbability

double

1.0

隨機允許存取機率(0~1)

executionTimeoutMs

int

100

單次採集逾時(ms)

預設限流:LOG/METRIC/SPAN/SPAN_TAG 約 5000 次/秒,SNAPSHOT 約 1 次/秒;行級探針另有全域約 100 次/秒保護。

Probe action 按類型填寫

LOG(taskType: live_debug_log_probe)

在目標點輸出動態日誌;不做對象圖序列化。

action 欄位

欄位

類型

必填

說明

type

string

固定 "LOG"

template

string

日誌模板,{expression} 文法

LOG 探針只渲染模板,會忽略 capture 維度。需要采參數/傳回值/棧請用 SNAPSHOT。

樣本:

{
  "probeType": "LOG",
  "language": "python",
  "target": {
    "typeName": "app.service.order",
    "methodName": "OrderService.create_order",
    "location": "exit",
    "instanceIds": ["*"]
  },
  "action": {
    "type": "LOG",
    "template": "create_order id={order_id} amount={amount} ret={@return} cost={@duration}ms"
  },
  "ttl": "30m",
  "captureCount": 100
}

SNAPSHOT(taskType: live_debug_snapshot_probe)

採集方法快照並做對象圖序列化上報。

action 欄位

欄位

類型

必填

說明

type

string

固定 "SNAPSHOT"

capture

string[]

採集維度枚舉;不傳或 [] 表示不採任何對象圖

captureExpressions

string[]

額外求值運算式列表

captureConfig

object

對象圖序列化預算

capture 枚舉

說明

ARGS

序列化方法參數

RETURN

序列化傳回值

THIS

序列化當前執行個體

EXCEPTION

記錄異常摘要

LOCALS

採集局部變數(依賴調試資訊)

STACK

採集調用棧(opt-in,需顯式包含)

EXECUTION_DETAIL

方法體內子調用彙總

captureConfig

欄位

預設

說明

maxDepth

3

對象序列化最大深度

maxCollectionSize

100

集合/數組最大元素數

maxStringLength

1024

字串最大長度

maxFieldCount

50

對象最大欄位數

maxTotalSizeBytes

65536

單次快照最大位元組數

stackTraceDepth

50

調用棧最大深度

redactedFieldPatterns

[".*password.*",".*token.*",".*secret.*"]

脫敏欄位正則

captureExpressions

文法同 trigger.condition / LOG 模板(受限 eval)。結果寫入 context.evaluatedExpressions,每項形如:

{"name": "order_id", "type": "...", "value": "...", "notCapturedReason": null}

求值失敗時 value=nullnotCapturedReason 記錄原因,不影響其它維度。captureExpressionscapture 相互獨立。

樣本:

{
  "probeType": "SNAPSHOT",
  "language": "python",
  "target": {
    "typeName": "app.service.order",
    "methodName": "OrderService.create_order",
    "location": "exit",
    "instanceIds": ["*"]
  },
  "trigger": {
    "condition": "@return is None or amount > 10000"
  },
  "action": {
    "type": "SNAPSHOT",
    "capture": ["ARGS"],
    "captureExpressions": ["order_id", "amount * count", "self.user_id", "@return"],
    "captureConfig": {
      "maxDepth": 3,
      "maxCollectionSize": 100,
      "maxStringLength": 1024
    }
  },
  "ttl": "30m",
  "captureCount": 50
}

METRIC(taskType: live_debug_metric_probe)

在目標點產生自訂指標,寫入監控系統。

action 欄位

欄位

類型

必填

說明

type

string

固定 "METRIC"

metricName

string

指標名,如 livedebug.order.amount

metricType

string

COUNTER / GAUGE / HISTOGRAM / SUMMARY

valueExpression

string

指標值的 Python 運算式

tags

object

標籤 map;值是 Python 運算式字串

樣本:

{
  "probeType": "METRIC",
  "language": "python",
  "target": {
    "typeName": "app.service.order",
    "methodName": "OrderService.create_order",
    "location": "exit",
    "instanceIds": ["*"]
  },
  "action": {
    "type": "METRIC",
    "metricName": "livedebug.order.amount",
    "metricType": "HISTOGRAM",
    "valueExpression": "amount",
    "tags": {
      "is_vip": "str(user_id == 'vip')"
    }
  },
  "ttl": "1h"
}

SPAN(taskType: live_debug_span_probe)

在目標函數執行期間建立 OTel Span;異常時標記 ERROR 並記錄 exception event。僅函數級。

action 欄位

欄位

類型

必填

說明

type

string

固定 "SPAN"

spanName

string

Span 名稱

spanTags

object

屬性 map;值為 Python 運算式字串

樣本:

{
  "probeType": "SPAN",
  "language": "python",
  "target": {
    "typeName": "app.service.order",
    "methodName": "OrderService.create_order",
    "location": "enter",
    "instanceIds": ["*"]
  },
  "action": {
    "type": "SPAN",
    "spanName": "dyn.create_order",
    "spanTags": {
      "order.id": "str(order_id)",
      "order.amount": "str(amount)"
    }
  },
  "ttl": "1h"
}

SPAN_TAG(taskType: live_debug_span_tag_probe)

給當前活躍 Span 追加屬性;無活躍 Span 時靜默跳過。

action 欄位

欄位

類型

必填

說明

type

string

固定 "SPAN_TAG"

tags

array

標籤數組,每項 { "key": "...", "value": "<Python 運算式>" }。注意:與 METRIC 的 tags(object map 格式)不同,此處為數組格式

樣本:

{
  "probeType": "SPAN_TAG",
  "language": "python",
  "target": {
    "typeName": "app.service.order",
    "methodName": "OrderService.create_order",
    "location": "exit",
    "instanceIds": ["*"]
  },
  "action": {
    "type": "SPAN_TAG",
    "tags": [
      {"key": "order.id", "value": "str(order_id)"},
      {"key": "order.result", "value": "str(@return)"}
    ]
  },
  "ttl": "1h"
}

錯誤與注意事項

現象

可能原因

處理建議

ProjectNotExist

SLS region 不正確

aliyun sls --region 顯式傳入與 Project 同地區

List 結果為空白但任務存在

type 與實際 taskType 不一致

按精確類型分別 List

建立 enabled:false 後探針仍在

不會影響已下發任務

使用 DeleteServiceTask 刪除任務

探針無資料

instanceIds 為空白、模組名錯誤、未觸發流量

["*"];核對 typeName/methodName;打流量後查 Status

SPAN 建立失敗或無效

使用了 line:N

改為函數級 enter/exit

ttl 異常

使用了 ms 單位

改用 s/m/h/d 或純秒數

完整調用鏈路樣本(LOG 探針)

# 0. 環境
REGION=cn-hangzhou
SLS_PROJECT=proj-xtrace-xxxxxxxxxxxxxxxxxxxxxx-cn-hangzhou
WORKSPACE=default-cms-xxxxxxxxxxxxxxxxxx-cn-hangzhou
SERVICE_ID='ggxw4lnjuz@f2fd3a6265a254a052afb'

# 1. 建立
RESP=$(aliyun cms2 apm service-task create \
  --workspace "$WORKSPACE" --service-id "$SERVICE_ID" \
  --type live_debug_log_probe --ip '*' \
  --task-config '{"probeType":"LOG","language":"python","target":{"typeName":"app.service.order","methodName":"OrderService.create_order","location":"exit","instanceIds":["*"]},"action":{"type":"LOG","template":"id={order_id} ret={@return}"},"ttl":"30m","captureCount":50}' \
  --region "$REGION" -o json)
echo "$RESP"
TASK_ID=$(echo "$RESP" | python3 -c 'import sys,json; print(json.load(sys.stdin)["data"]["taskId"])')

# 2. 確認任務
aliyun cms2 apm service-task get \
  --workspace "$WORKSPACE" --service-id "$SERVICE_ID" \
  --task-id "$TASK_ID" --type live_debug_log_probe \
  --region "$REGION" -o json

# 3. 觸發業務後查結果(最近 10 分鐘)
FROM=$(( $(date +%s) - 600 )); TO=$(date +%s)
aliyun sls get-logs-v2 --region "$REGION" --accept-encoding gzip \
  --project "$SLS_PROJECT" --logstore logstore-apm-logs \
  --from "$FROM" --to "$TO" \
  --query "* and \"$TASK_ID\" | SELECT content FROM log WHERE json_extract_scalar(attributes, '\$[\"livedebug.report_type\"]') != 'status'"

# 4. 清理
aliyun cms2 apm service-task delete \
  --workspace "$WORKSPACE" --service-id "$SERVICE_ID" \
  --task-id "$TASK_ID" --type live_debug_log_probe \
  --region "$REGION" -o json