SuperAPI AI Directory

aliyun-sls-skills

Deployment & operations

View repository

Updated 10-16 06:47

About this skill

Capability Overview

Directory Structure

aliyun-sls-skills/
├── SKILL.md
├── .env.example
├── reference/                    # API 定义(YML),含入参与返回值
│   ├── list_project.yml
│   ├── list_logstores.yml
│   └── get_log_v2.yml
└── scripts/
    ├── sls_util.py               # 凭证与 Client 构造(供脚本复用)
    ├── list_project.py
    ├── list_logstores.py
    ├── get_logs_v2.py
    └── requirements.txt
  • reference/: stores API-related information (YML fragments), for consulting parameter and response meanings.
  • scripts/: ready-to-run examples (e.g., under the aliyun-sls-skills directory, run python scripts/list_logstores.py ...); you can also read the implementation and modify it.
  • Dependencies:pip install -r aliyun-sls-skills/scripts/requirements.txt。

This skill provides the followingindependent capabilities, which can be combined as needed:

Capability API Purpose Use Case
List Projects ListProject List SLS Projects under the account Confirm project names, browse with pagination
List logstores ListLogStores List LogStores under a Project Confirm logstore names, browse with pagination
Query logs GetLogsV2 Pull logs by time range and query statement Search error logs, SQL analysis, scan mode

Notes:

  • If the user is unsure of the project name, they can first ListProject to view all projects under the account.
  • If the user is unsure of the logstore name, they can first ListLogStores then GetLogsV2。
  • GetLogsV2 The time interval isleft-closed, right-open [from, to), and must satisfy from < to。
  • In the Python SDK, request parameter field names are based on alibabacloud_sls20201230.models (e.g., GetLogsV2Request uses from_、to, not from_time / to_time)。

Project configuration file (.aliyun-config.json)

Save SLS-related context information tothe current working directoryunder .aliyun-config.json, so that subsequent operations can reuse the confirmed region, project, logstore, and other configurations, avoiding repeated inquiries. Two formats are supported:

Single-project configuration (object format)

{
  "version": 1,
  "sls": [
    {
      "region": "cn-hangzhou",
      "project": "prod-sls-project",
      "logstores": ["app-logs", "nginx-logs", "access-logs"],
      "default_logstore": "app-logs",
      "last_query_at": "2026-04-01T12:00:00Z"
    },
    {
      "region": "cn-beijing",
      "project": "backup-sls-project",
      "logstores": ["archive-logs"],
      "default_logstore": "archive-logs",
      "last_query_at": "2026-03-28T10:00:00Z"
    }
  ]
}

Multi-project configuration (array format)

Supports managing SLS configurations for multiple applications/environments in the same repository:

[
  {
    "project": "web-app",
    "version": 1,
    "sls": [
      {
        "region": "cn-hangzhou",
        "project": "web-prod",
        "logstores": ["frontend", "backend", "nginx"],
        "default_logstore": "backend",
        "last_query_at": "2026-04-01T12:00:00Z"
      },
      {
        "region": "cn-shanghai",
        "project": "web-dr",
        "logstores": ["frontend", "backend"],
        "default_logstore": "backend",
        "last_query_at": "2026-04-01T11:00:00Z"
      }
    ]
  },
  {
    "project": "data-platform",
    "version": 1,
    "sls": [
      {
        "region": "cn-beijing",
        "project": "etl-logs",
        "logstores": ["spark", "flink", "kafka"],
        "default_logstore": "spark",
        "last_query_at": "2026-04-01T10:00:00Z"
      }
    ]
  }
]

Field Description:

Field Type Required Description
project string Required for multiple projects Configuration project identifier name (e.g., application name, environment name), used to distinguish different configurations
version int Yes Configuration format version, currently 1
sls array Yes SLS configuration list, each element corresponds to one SLS Project (can span regions)
sls[].region string Yes The region where this SLS Project is located (e.g., cn-hangzhou)
sls[].project string Yes SLS Project name
sls[].logstores array Yes List of LogStore names under this Project
sls[].default_logstore string No Default LogStore name to use
sls[].last_query_at string No Last query time in ISO 8601 format

Reading Rules

Before performing SLS operations,first check whether the current working directory contains .aliyun-config.json:

import json
import os

config_path = os.path.join(os.getcwd(), ".aliyun-config.json")
sls_entries = []

if os.path.exists(config_path):
    with open(config_path, "r", encoding="utf-8") as f:
        config = json.load(f)
        # 数组格式(多项目):提示用户选择项目
        if isinstance(config, list):
            # 展示项目列表供用户选择
            projects = [item.get("project", f"项目{i}") for i, item in enumerate(config)]
            # 用户选择后获取该项目的 sls 列表
            selected = config[selected_index]
            sls_entries = selected.get("sls", [])
        # 对象格式(单项目):直接使用 sls 列表
        else:
            sls_entries = config.get("sls", [])

# sls_entries 是列表,包含多个 {region, project, logstores, ...}
# 若存在多个,提示用户选择具体的 project+logstore

Configuration Reuse Logic:

  1. Single configuration: if sls The list contains only one configuration, and the fields are complete, so it can be reused directly.
  2. Multiple configurations: If the sls list contains multiple entries (multiple Projects or multiple regions), prompt the user to select the specific region + project + logstore。
  3. Multiple project format: first select the outer project field, then select the specific configuration from its sls list.
  4. If the user explicitly requests to change region, project, or logstore, you must reconfirm and update the configuration.
  5. If the configuration file does not exist or fields are missing, you need to first query through ListProject / ListLogStores and other APIs, thenhave the user select or confirm before writing.

Write rules

Update at the following times .aliyun-config.json:

  1. after the user first confirms region, project, logstore: write the sls list.
  2. After each successful query execution: update the corresponding entry's last_query_at。
  3. When the user changes the target resource: update or append the corresponding entry.
  4. When adding a new project configuration: append a new project in array format.

Single-project configuration write example

import json
import os
from datetime import datetime, timezone

config_path = os.path.join(os.getcwd(), ".aliyun-config.json")

# 读取现有配置(若存在)
config = {}
if os.path.exists(config_path):
    with open(config_path, "r", encoding="utf-8") as f:
        config = json.load(f)

# 更新 sls 列表
config["version"] = config.get("version", 1)
config["sls"] = [
    {
        "region": "cn-hangzhou",
        "project": "prod-sls",
        "logstores": ["app", "nginx"],
        "default_logstore": "app",
        "last_query_at": datetime.now(timezone.utc).isoformat()
    },
    {
        "region": "cn-beijing",
        "project": "backup-sls",
        "logstores": ["archive"],
        "default_logstore": "archive",
        "last_query_at": "2026-03-28T10:00:00Z"
    }
]

# 写入
with open(config_path, "w", encoding="utf-8") as f:
    json.dump(config, f, indent=2, ensure_ascii=False)

Multi-project configuration write example

import json
import os
from datetime import datetime, timezone

config_path = os.path.join(os.getcwd(), ".aliyun-config.json")

# 读取现有配置(若存在)
config = []
if os.path.exists(config_path):
    with open(config_path, "r", encoding="utf-8") as f:
        content = f.read().strip()
        if content:
            loaded = json.loads(content)
            config = loaded if isinstance(loaded, list) else [loaded]

# 查找或创建项目配置
project_name = "web-app"  # 用户指定的项目名
existing = next((item for item in config if item.get("project") == project_name), None)

new_entry = {
    "project": project_name,
    "version": 1,
    "sls": [
        {
            "region": "cn-hangzhou",
            "project": "web-prod",
            "logstores": ["frontend", "backend"],
            "default_logstore": "backend",
            "last_query_at": datetime.now(timezone.utc).isoformat()
        }
    ]
}

if existing:
    # 更新现有项目的 sls 列表
    existing["sls"] = new_entry["sls"]
    existing["version"] = new_entry["version"]
else:
    # 追加新项目配置
    config.append(new_entry)

# 写入
with open(config_path, "w", encoding="utf-8") as f:
    json.dump(config, f, indent=2, ensure_ascii=False)

Shared with other skills

.aliyun-config.json may contain configurations for multiple Alibaba Cloud products (such as oss、cdn、domain , etc.).This skill only reads and writes the sls field, and must not overwrite or delete configuration sections of other products.

{
  "version": 1,
  "sls": { "region": "cn-hangzhou", "project": "..." },
  "oss": { "bucket": "...", "region": "..." },
  "cdn": { "domain": "..." }
}

Security notice

  • Do not store sensitive credentials such as AK/SK in the configuration file; credentials should be managed through environment variables or .env .
  • Whether to .aliyun-config.json commit to the version repository is decided by team conventions (recommended to add to .gitignore)。

Pre-check (must be performed first)

Before calling SLS, you must confirm that access credentials are configured.

Check order

1. Environment variables

echo "AK_ID: ${ALIBABA_CLOUD_ACCESS_KEY_ID:+已设置}"
echo "AK_SECRET: ${ALIBABA_CLOUD_ACCESS_KEY_SECRET:+已设置}"

2. Current directory .env

find . -maxdepth 1 -name ".env" -exec cat {} \;

For examples, see .env.example。

3. Loading in Python (consistent with scripts behavior)

from dotenv import load_dotenv
import os

access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID", "").strip()
access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "").strip()

if not access_key_id or not access_key_secret:
    load_dotenv()
    access_key_id = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_ID", "").strip()
    access_key_secret = os.environ.get("ALIBABA_CLOUD_ACCESS_KEY_SECRET", "").strip()

if not access_key_id or not access_key_secret:
    raise RuntimeError("缺少 ALIBABA_CLOUD_ACCESS_KEY_ID / ALIBABA_CLOUD_ACCESS_KEY_SECRET")

If the credential check is not passed, you should not continue calling the API.


Install dependencies

pip install -r aliyun-sls-skills/scripts/requirements.txt

or install manually (consistent with other Tea SDK skills in the repository):

pip install alibabacloud_sls20201230 alibabacloud_credentials alibabacloud_tea_openapi alibabacloud_tea_util python-dotenv

Create SLS Client

endpoint The format is {region}.log.aliyuncs.com. The example script uses scripts/sls_util.py 's create_sls_client(region) through Explicit AK/SK(same as aliyun-domain-skills/scripts/query_domainlist.py ).

If you need an AK-less chain (ECS role, OIDC, etc.), you can switch to using CredentialClient() to pass in open_api_models.Config(credential=credential), and still set endpoint。

from alibabacloud_sls20201230.client import Client as Sls20201230Client
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models

credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = f"{region}.log.aliyuncs.com"
client = Sls20201230Client(config)

ListProject

List the matching Project information under the current account. For complete fields, see reference/list_project.yml。

Common parameters (summary)

Concept SDK field Description
projectName project_name Project name, supports fuzzy matching
offset offset Query start row, default 0
size size Number of rows per page, default 500, maximum 500
resourceGroupId resource_group_id Resource group ID
fetchQuota fetch_quota Whether to obtain Project quota information

Core process

  1. create_client() Create SLS Client (using credential chain or explicit AK/SK)
  2. Build ListProjectRequest
  3. client.list_project_with_options(request, headers, runtime)
  4. Use resp.body.to_map() to get a dictionary

Example script:scripts/list_project.py

Command-line example

cd aliyun-sls-skills
python scripts/list_project.py

Code example

from alibabacloud_sls20201230.client import Client as Sls20201230Client
from alibabacloud_sls20201230 import models as sls_models
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
import json

credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = "cn-hangzhou.log.aliyuncs.com"
client = Sls20201230Client(config)

request = sls_models.ListProjectRequest(project_name="test", size=10)
runtime = util_models.RuntimeOptions()
resp = client.list_project_with_options(request, {}, runtime)
print(json.dumps(resp.body.to_map(), default=str, indent=2, ensure_ascii=False))

Response(body, common fields):total、count、projects etc., subject to the actual response.


ListLogStores

List the specified project LogStore under . For the complete fields, see reference/list_logstores.yml。

Common parameters (summary)

Concept SDK field Description
project Method parameter project Required
logstoreName logstore_name Fuzzy match filtering
offset / size offset / size Pagination, size max 500, default 200
telemetryType telemetry_type Logs / Metrics
mode mode standard / query

Core flow

  1. create_sls_client(region)
  2. Build ListLogStoresRequest
  3. client.list_log_stores_with_options(project, request, {}, runtime)
  4. Use resp.body.to_map() to get the dictionary

Example script:scripts/list_logstores.py

Command-line example

cd aliyun-sls-skills
python scripts/list_logstores.py --region cn-hangzhou --project your-project
python scripts/list_logstores.py --region cn-hangzhou --project your-project --logstore-name app

Code example

from alibabacloud_sls20201230 import models as sls_models
from alibabacloud_tea_util import models as util_models
import json

from sls_util import create_sls_client

client = create_sls_client("cn-hangzhou")
request = sls_models.ListLogStoresRequest(logstore_name="error")
runtime = util_models.RuntimeOptions()
resp = client.list_log_stores_with_options("your-project", request, {}, runtime)
print(json.dumps(resp.body.to_map(), default=str, indent=2, ensure_ascii=False))

Response(body, common fields):total、count、logstores etc., subject to the actual response.


GetLogsV2

On the specified project、logstore query by time range. For the complete description, see reference/get_log_v2.yml。

Common parameters (summary)

Concept SDK field Description
from (Unix seconds) from_ Left end of the interval (inclusive)
to (Unix seconds) to Right end of the interval (exclusive)
query query Search or SQL analysis statement
line / offset line / offset Pagination under the search statement, line max 100
reverse reverse Whether to sort in reverse time order (for search statements)
topic topic Topic
powerSql power_sql SQL enhancement
session session e.g. mode=scan
Accept-Encoding GetLogsV2Headers(accept_encoding=...) e.g. lz4、gzip

If query is an analysis statement,line/offset often does not take effect; please use SQL LIMIT etc. for pagination (see the official documentation).

Core flow

  1. Build GetLogsV2Request(from_=..., to=..., query=..., ...)
  2. headers = GetLogsV2Headers(accept_encoding="lz4")(or gzip)
  3. client.get_logs_v2with_options(project, logstore, request, headers, runtime)
  4. resp.body.to_map() — usually includes meta、data

Example script:scripts/get_logs_v2.py

Command-line example

python scripts/get_logs_v2.py --region cn-hangzhou --project your-project --logstore your-logstore --recent-minutes 15 --query "error"
python scripts/get_logs_v2.py --region cn-hangzhou --project your-project --logstore your-logstore \
  --from-time 1700000000 --to-time 1700003600 --query '* | SELECT count(*) AS cnt'
python scripts/get_logs_v2.py --region cn-hangzhou --project your-project --logstore your-logstore \
  --from-time 1700000000 --to-time 1700003600 --query '*' --session "mode=scan"

Code example

import time
from alibabacloud_sls20201230 import models as sls_models
from alibabacloud_tea_util import models as util_models
import json

from sls_util import create_sls_client

client = create_sls_client("cn-hangzhou")
now = int(time.time())
request = sls_models.GetLogsV2Request(
    query="error",
    from_=now - 900,
    to=now,
    line=100,
    offset=0,
    reverse=False,
)
headers = sls_models.GetLogsV2Headers(accept_encoding="lz4")
runtime = util_models.RuntimeOptions()
resp = client.get_logs_v2with_options("your-project", "your-logstore", request, headers, runtime)
print(json.dumps(resp.body.to_map(), default=str, indent=2, ensure_ascii=False))

Error handling

try:
    resp = client.get_logs_v2with_options(project, logstore, request, headers, runtime)
except Exception as error:
    print(getattr(error, "message", str(error)))
    if hasattr(error, "data") and error.data:
        print(error.data.get("Recommend", ""))

The script uses scripts/sls_util.py in print_operation_error for similar output.

Common cases Description
401/403 Insufficient AK/SK or RAM permissions
ProjectNotExist Wrong Project name or region
LogStoreNotExist First use ListLogStores to verify the name
ParameterInvalid Invalid parameters such as time interval, query syntax, offset, etc.

Usage flow summary

  1. Check the environment variables or .env the AK/SK in .
  2. Install scripts/requirements.txt。
  3. Check whether .aliyun-config.json already has an SLS configuration (sls list); if it exists and matches the intent, it can be reused directly.
  4. If the configuration contains multiple sls entries or a multi-project configuration, prompt the user to select a specific region + project + logstore.
  5. If unsure of the project name, first ListProject to view the projects under the account.
  6. Confirm region、project; if unsure of the logstore, first ListLogStores。
  7. GetLogsV2 pass in a valid time interval and query, parse body the meta / data。
  8. after the operation succeeds, update .aliyun-config.json the corresponding entry in last_query_at。

Notes

  • reference/ is used to check the contract;scripts/ Used to verify the environment and invocation method.
  • When the business and examples do not match, refer to the official SLS documentation and the current SDK model.