All Products
Search
Document Center

Simple Log Service:Mengelola alert menggunakan SDK Simple Log Service untuk Python

Last Updated:Dec 12, 2025

Topik ini menjelaskan cara mengelola alert menggunakan SDK Simple Log Service untuk Python dan menyediakan contoh kode.

Prasyarat

Metode penagihan

Biaya untuk fitur alerting hanya dikenakan saat Anda menerima notifikasi alert melalui SMS dan panggilan suara. Untuk informasi selengkapnya, lihat Harga Simple Log Service.

Metode notifikasi

Deskripsi

Pesan SMS

Biaya dikenakan berdasarkan jumlah notifikasi alert yang diterima melalui SMS.

Catatan

Jika pesan SMS melebihi 70 karakter, pesan akan dikirim sebagai dua SMS terpisah, tetapi Anda hanya akan ditagih untuk satu pesan.

Panggilan suara

Biaya dikenakan berdasarkan jumlah notifikasi alert yang diterima melalui panggilan suara.

Catatan
  • Jika panggilan suara tidak terjawab, notifikasi SMS akan dikirim.

  • Anda hanya dikenakan biaya satu kali untuk panggilan suara, baik panggilan dijawab maupun tidak. Notifikasi SMS tersebut tidak dikenakan biaya.

Mengelola aturan alert

Contoh kode berikut menunjukkan cara mengelola aturan alert. Untuk informasi selengkapnya tentang parameter dalam kode, lihat Struktur Data Aturan Peringatan.

import os
from aliyun.log import LogClient
# Endpoint Simple Log Service. 
endpoint = 'cn-huhehaote.log.aliyuncs.com'
# Konfigurasikan variabel lingkungan. Dalam contoh ini, ID AccessKey dan Rahasia AccessKey diperoleh dari variabel lingkungan. 
accesskey_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accesskey_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# Buat klien Simple Log Service. 
client = LogClient(endpoint, accesskey_id, accesskey_secret)

project = 'demo-alert'
alert_id = 'nginx-status-error'


def create_alert():
    alert = {
        'name': alert_id,
        'displayName': 'Nginx Status Error',
        'type': 'Alert',
        'status': 'Enabled',
        'schedule': {
            'type': 'FixedRate',
            'interval': '1m'
        },
        'configuration': {
            'version': '2.0',
            'type': 'default',
            'dashboard': 'internal-alert-analysis',
            'queryList': [{
                # Jenis data peringatan. Nilai valid: log, metric, dan meta. Nilai log menentukan Logstore. Nilai metric menentukan Metricstore. Nilai meta menentukan data resource.
                'storeType': 'log',
                # Wilayah yang didukung.
                'region': 'cn-huhehaote',
                # Nama proyek.
                'project': 'demo-alert',
                # Nama Logstore atau Metricstore.
                'store': 'nginx-access-log',
                # Pernyataan query.
                'query': 'status >= 400 | select count(*) as cnt',
                # Jenis rentang waktu.
                'timeSpanType': 'Truncated',
                # Waktu mulai.
                'start': '-1m',
                # Waktu akhir.
                'end': 'absolute',
                # Tentukan apakah akan mengaktifkan SQL Khusus.
                'powerSqlMode': 'auto'
            }],
            'groupConfiguration': {
                'type': 'no_group',
                'fields': []
            },
            'joinConfigurations': [],
            'severityConfigurations': [{
                'severity': 6,
                'evalCondition': {
                    'condition': 'cnt > 0',
                    'countCondition': ''
                }
            }],
            'labels': [{
                'key': 'service',
                'value': 'nginx'
            }],
            'annotations': [{
                'key': 'title',
                'value': 'Nginx Status Error'
            }, {
                'key': 'desc',
                'value': 'Nginx Status Error, count: ${cnt}'
            }],
            'autoAnnotation': True,
            'sendResolved': False,
            'threshold': 1,
            'noDataFire': False,
            'noDataSeverity': 6,
            'policyConfiguration': {
                'alertPolicyId': 'sls.builtin.dynamic',
                'actionPolicyId': 'test-action-policy',
                'repeatInterval': '1m',
                'useDefault': False
            }
        }
    }
    res = client.create_alert(project, alert)
    res.log_print()


def get_and_update_alert():
    res = client.get_alert(project, alert_id)
    res.log_print()

    alert = res.get_body()
    alert['configuration']['queryList'][0]['query'] = 'status >= 400 | select count(*) as cnt'
    res = client.update_alert(project, alert)
    res.log_print()


def enable_and_disable_alert():
    res = client.disable_alert(project, alert_id)
    res.log_print()

    res = client.enable_alert(project, alert_id)
    res.log_print()


def list_alerts():
    res = client.list_alert(project, offset=0, size=100)
    res.log_print()


def delete_alert():
    res = client.delete_alert(project, alert_id)
    res.log_print()


if __name__ == '__main__':
    create_alert()
    get_and_update_alert()
    enable_and_disable_alert()
    list_alerts()
    delete_alert()

Mengelola data resource alert

Contoh kode berikut menunjukkan cara mengelola data resource alert. Untuk informasi selengkapnya tentang parameter dalam kode, lihat Struktur data resource alert.

Manage user

import os
from aliyun.log import LogClient
from aliyun.log.resource_params import ResourceRecord
# Endpoint Simple Log Service. Untuk data resource, operasi tulis hanya mendukung endpoint Simple Log Service untuk wilayah China (Heyuan), dan operasi baca mendukung endpoint Simple Log Service untuk wilayah lainnya. 
endpoint = 'cn-heyuan.log.aliyuncs.com'
# Konfigurasikan variabel lingkungan. Dalam contoh ini, ID AccessKey dan Rahasia AccessKey diperoleh dari variabel lingkungan. 
accesskey_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accesskey_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# Buat klien Simple Log Service. 
client = LogClient(endpoint, accesskey_id, accesskey_secret)
user_resource_name = 'sls.common.user'


def create_user():
    user = {
        'user_id': 'alex',
        'user_name': 'Alex',
        'email': [
            '****@example.com'
        ],
        'country_code': '86',
        'phone': '133****3333',
        'enabled': True,
        'sms_enabled': True,
        'voice_enabled': True
    }
    record = ResourceRecord(user['user_id'], user['user_name'], user)
    res = client.create_resource_record(user_resource_name, record)
    print('[buat pengguna]')
    res.log_print()


def get_user():
    res = client.get_resource_record(user_resource_name, 'alex')
    print('[dapatkan pengguna]')
    print(res.get_record().to_dict())


def update_user():
    user = {
        'user_id': 'alex',
        'user_name': 'Alex',
        'email': [
            '****@example.com'
        ],
        'country_code': '86',
        'phone': '133****3333',
        'enabled': False,
        'sms_enabled': True,
        'voice_enabled': True
    }
    record = ResourceRecord(user['user_id'], user['user_name'], user)
    res = client.update_resource_record(user_resource_name, record)
    print('[perbarui pengguna]')
    res.log_print()


def list_users():
    res = client.list_resource_records(user_resource_name, offset=0, size=100)
    print('[daftar pengguna]')
    print([r.to_dict() for r in res.get_records()])


def delete_user():
    res = client.delete_resource_record(user_resource_name, ['alex'])
    print('[hapus pengguna]')
    res.log_print()


if __name__ == '__main__':
    create_user()
    get_user()
    update_user()
    list_users()
    delete_user()

Manage user groups

def create_user_group():
    user_group = {
        'user_group_id': 'devops',
        'user_group_name': 'Tim DevOps',
        'enabled': True,
        'members': ['alex']
    }
    record = ResourceRecord(user_group['user_group_id'], user_group['user_group_name'], user_group)
    res = client.create_resource_record('sls.common.user_group', record)
    print('[buat grup pengguna]')
    res.log_print()

Manage webhook integration

def create_webhook_integration():
    webhooks = [{
        'id': 'dingtalk',
        'name': 'Dingtalk Webhook',
        'type': 'dingtalk',
        'url': 'https://oapi.dingtalk.com/robot/send?access_token=**********',
        'method': 'POST',
        # Nilai Additional Signature untuk chatbot DingTalk Anda. Jika Anda memilih Additional Signature untuk Pengaturan Keamanan saat membuat chatbot DingTalk, Anda harus mengonfigurasi bidang ini. Anda dapat memperoleh nilai Additional Signature pada halaman manajemen chatbot DingTalk. 
        # 'secret': 'SEC**********',
        'headers': []
    }, {
        'id': 'wechat',
        'name': 'Wechat Webhook',
        'type': 'wechat',
        'url': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=**********',
        'method': 'POST',
        'headers': []
    }, {
        'id': 'feishu',
        'name': 'Feishu Webhook',
        'type': 'lark',
        'url': 'https://open.feishu.cn/open-apis/bot/v2/hook/**********',
        'method': 'POST',
        # Nilai Verifikasi Signature untuk bot Lark Anda. Jika Anda memilih Verifikasi Signature untuk Pengaturan Keamanan saat membuat bot Lark, Anda harus mengonfigurasi bidang ini. Anda dapat memperoleh nilai Verifikasi Signature pada halaman manajemen bot Lark. 
        # 'secret': '**********',
        'headers': []
    }, {
        'id': 'slack',
        'name': 'Slack Webhook',
        'type': 'slack',
        'url': 'https://hooks.slack.com/services/**********',
        'method': 'POST',
        'headers': []
    }, {
        'id': 'webhook',
        'name': 'Webhook Umum',
        'type': 'custom',
        'url': 'https://example.com/***********',
        'method': 'POST',
        'headers': [{
            'key': 'Authorization',
            'value': 'Basic YWRtaW46Zm9vYmFy'
        }]
    }]

    for webhook in webhooks:
        record = ResourceRecord(webhook['id'], webhook['name'], webhook)
        res = client.create_resource_record('sls.alert.action_webhook', record)
        print('[buat integrasi webhook] ' + webhook['id'])
        res.log_print()

Manage action policies

def create_action_policy():
    action_policy = {
        'action_policy_id': 'test-action-policy',
        'action_policy_name': 'Kebijakan Tindakan Uji',
        'primary_policy_script': 'fire(type="sms", users=["alex"], groups=[], oncall_groups=[], receiver_type="static", external_url="", external_headers={}, template_id="sls.builtin.cn", period="any")',
        'secondary_policy_script': 'fire(type="voice", users=["alex"], groups=[], oncall_groups=[], receiver_type="static", external_url="", external_headers={}, template_id="sls.builtin.cn", period="any")',
        'escalation_start_enabled': False,
        'escalation_start_timeout': '10m',
        'escalation_inprogress_enabled': False,
        'escalation_inprogress_timeout': '30m',
        'escalation_enabled': True,
        'escalation_timeout': '1h'
    }
    record = ResourceRecord(
        action_policy['action_policy_id'], action_policy['action_policy_name'], action_policy)
    res = client.create_resource_record('sls.alert.action_policy', record)
    print('[buat kebijakan tindakan]')
    res.log_print()

Manage alert policies

def create_alert_policy():
    alert_policy = {
        'policy_id': 'test-alert-policy',
        'policy_name': 'Kebijakan Peringatan Uji',
        'parent_id': '',
        'group_script': 'fire(action_policy="test-action-policy", group={"alert.alert_id": alert.alert_id}, group_by_all_labels=true, group_wait="15s", group_interval="5m", repeat_interval="1h")',
        'inhibit_script': '',
        'silence_script': ''
    }
    record = ResourceRecord(alert_policy['policy_id'], alert_policy['policy_name'], alert_policy)
    res = client.create_resource_record('sls.alert.alert_policy', record)
    print('[buat kebijakan peringatan]')
    res.log_print()

Manage alert templates

def create_content_template():
    template = {
        'template_id': 'test-template',
        'template_name': 'Templat Uji',
        'templates': {
            'sms': {
                'locale': 'zh-CN',
                'content': ''
            },
            'voice': {
                'locale': 'zh-CN',
                'content': ''
            },
            'email': {
                'locale': 'zh-CN',
                'subject': 'SLS Alert',
                'content': ''
            },
            'message_center': {
                'locale': 'zh-CN',
                'content': ''
            },
            'dingtalk': {
                'locale': 'zh-CN',
                'title': 'SLS Alert',
                'content': ''
            },
            'wechat': {
                'locale': 'zh-CN',
                'title': 'SLS Alert',
                'content': ''
            },
            'lark': {
                'locale': 'zh-CN',
                'title': 'SLS Alert',
                'content': ''
            },
            'slack': {
                'locale': 'zh-CN',
                'title': 'SLS Alert',
                'content': ''
            },
            'webhook': {
                'locale': 'zh-CN',
                'send_type': 'batch',
                'limit': 0,
                'content': ''
            },
            'fc': {
                'locale': 'zh-CN',
                'limit': 0,
                'send_type': 'batch',
                'content': ''
            },
            'event_bridge': {
                'locale': 'zh-CN',
                'subject': 'SLS Alert',
                'content': ''
            },
        }
    }
    record = ResourceRecord(template['template_id'], template['template_name'], template)
    res = client.create_resource_record('sls.alert.content_template', record)
    print('[buat templat konten]')
    res.log_print()