このページは機械翻訳によるものです。内容の正確さは保証しておりません。 人力翻訳を依頼する

Python 用 Simple Log Service SDK を使用してアラートを管理する

更新日時2025-03-14 17:36

このトピックでは、Python 用 Simple Log Service SDK を使用してアラートを管理する方法について説明し、サンプルコードを提供します。

前提条件

  • Simple Log Service が 有効化されている。

  • Python 用 Simple Log Service SDK が 初期化されている。

課金方法

アラート機能の場合、SMS メッセージと音声通話を使用してアラート通知を受信した場合にのみ課金されます。 詳細については、「Simple Log Service の価格」をご参照ください。

通知方法

説明

通知方法

説明

SMS メッセージ

SMS メッセージを使用して通知を受信すると、料金が発生します。 アラート通知を受信した回数に基づいて課金されます。

説明

SMS メッセージが 70 文字を超える場合は、2 つのメッセージで送信される場合があります。 この場合、1 回だけ課金されます。

音声通話

音声通話を使用して通知を受信すると、料金が発生します。 アラート通知を受信した回数に基づいて課金されます。

説明
  • 音声通話に応答がない場合は、SMS 通知が送信されます。

  • 通話に応答したかどうかにかかわらず、音声通話に対して 1 回だけ課金されます。 通知メッセージは料金が発生しません。

アラートルールの管理

次のサンプルコードは、アラートルールを管理する方法の例を示しています。 サンプルコードのパラメーターの詳細については、「アラートルールのデータ構造」をご参照ください。

import os
from aliyun.log import LogClient
# Simple Log Service エンドポイント。
endpoint = 'cn-huhehaote.log.aliyuncs.com'
# 環境変数を構成します。 この例では、AccessKey ID と AccessKey シークレットは環境変数から取得されます。
accesskey_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accesskey_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# 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 ステータスエラー',
        'type': 'Alert',
        'state': 'Enabled',
        'schedule': {
            'type': 'FixedRate',
            'interval': '1m'
        },
        'configuration': {
            'version': '2.0',
            'type': 'default',
            'dashboard': 'internal-alert-analysis',
            'queryList': [{
                # アラートデータのタイプ。 有効な値:log、metric、および meta。 値 log は Logstore を指定します。 値 metric は Metricstore を指定します。 値 meta はリソースデータを指定します。
                'storeType': 'log',
                # サポートされているリージョン。
                'region': 'cn-huhehaote',
                # プロジェクトの名前。
                'project': 'demo-alert',
                # Logstore または Metricstore の名前。
                'store': 'nginx-access-log',
                # クエリ文。
                'query': 'status >= 400 | select count(*) as cnt',
                # 時間範囲のタイプ。
                'timeSpanType': 'Truncated',
                # 開始時刻。
                'start': '-1m',
                # 終了時刻。
                'end': 'absolute',
                # 専用 SQL を有効にするかどうかを指定します。
                '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 ステータスエラー'
            }, {
                'key': 'desc',
                'value': 'Nginx ステータスエラー、カウント:${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()

アラートリソースデータの管理

次のサンプルコードは、アラートリソースデータを管理する方法の例を示しています。 サンプルコードのパラメーターの詳細については、「アラートリソースデータのデータ構造」をご参照ください。

ユーザーの管理

import os
from aliyun.log import LogClient
from aliyun.log.resource_params import ResourceRecord
# Simple Log Service エンドポイント。 リソースデータの場合、書き込み操作は中国 (河源) リージョンの Simple Log Service エンドポイントのみをサポートし、読み取り操作は他のリージョンの Simple Log Service エンドポイントをサポートします。
endpoint = 'cn-heyuan.log.aliyuncs.com'
# 環境変数を構成します。 この例では、AccessKey ID と AccessKey シークレットは環境変数から取得されます。
accesskey_id = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accesskey_secret = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# 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('[ユーザーの作成]')
    res.log_print()


def get_user():
    res = client.get_resource_record(user_resource_name, 'alex')
    print('[ユーザーの取得]')
    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('[ユーザーの更新]')
    res.log_print()


def list_users():
    res = client.list_resource_records(user_resource_name, offset=0, size=100)
    print('[ユーザーのリスト]')
    print([r.to_dict() for r in res.get_records()])


def delete_user():
    res = client.delete_resource_record(user_resource_name, ['alex'])
    print('[ユーザーの削除]')
    res.log_print()


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

ユーザーグループの管理

def create_user_group():
    user_group = {
        'user_group_id': 'devops',
        'user_group_name': '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('[ユーザーグループの作成]')
    res.log_print()

Webhook 統合の管理

def create_webhook_integration():
    webhooks = [{
        'id': 'dingtalk',
        'name': 'DingTalk Webhook',
        'type': 'dingtalk',
        'url': 'https://oapi.dingtalk.com/robot/send?access_token=**********',
        'method': 'POST',
        # DingTalk チャットボットの追加署名の値。 DingTalk チャットボットを作成するときにセキュリティ設定で追加署名を選択した場合は、このフィールドを構成する必要があります。 追加署名の値は、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',
        # Lark ボットの署名検証の設定値。 Lark ボットを作成するときにセキュリティ設定で署名検証の設定を選択した場合は、このフィールドを構成する必要があります。 署名検証の設定値は、Lark のボット管理ページで取得できます。
        # 'secret': '**********',
        'headers': []
    }, {
        'id': 'slack',
        'name': 'Slack Webhook',
        'type': 'slack',
        'url': 'https://hooks.slack.com/services/**********',
        'method': 'POST',
        'headers': []
    }, {
        'id': 'webhook',
        'name': '共通 Webhook',
        '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('[Webhook 統合の作成] ' + webhook['id'])
        res.log_print()

アクションポリシーの管理

def create_action_policy():
    action_policy = {
        'action_policy_id': 'test-action-policy',
        'action_policy_name': 'テストアクションポリシー',
        '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('[アクションポリシーの作成]')
    res.log_print()

アラートポリシーの管理

def create_alert_policy():
    alert_policy = {
        'policy_id': 'test-alert-policy',
        'policy_name': 'テストアラートポリシー',
        '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('[アラートポリシーの作成]')
    res.log_print()

アラートテンプレートの管理

def create_content_template():
    template = {
        'template_id': 'test-template',
        'template_name': 'テストテンプレート',
        'templates': {
            'sms': {
                'locale': 'zh-CN',
                'content': ''
            },
            'voice': {
                'locale': 'zh-CN',
                'content': ''
            },
            'email': {
                'locale': 'zh-CN',
                'subject': 'SLS アラート',
                'content': ''
            },
            'message_center': {
                'locale': 'zh-CN',
                'content': ''
            },
            'dingtalk': {
                'locale': 'zh-CN',
                'title': 'SLS アラート',
                'content': ''
            },
            'wechat': {
                'locale': 'zh-CN',
                'title': 'SLS アラート',
                'content': ''
            },
            'lark': {
                'locale': 'zh-CN',
                'title': 'SLS アラート',
                'content': ''
            },
            'slack': {
                'locale': 'zh-CN',
                'title': 'SLS アラート',
                '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 アラート',
                'content': ''
            },
        }
    }
    record = ResourceRecord(template['template_id'], template['template_name'], template)
    res = client.create_resource_record('sls.alert.content_template', record)
    print('[コンテンツテンプレートの作成]')
    res.log_print()
  • 目次 (1, M)
  • 前提条件
  • 課金方法
  • アラートルールの管理
  • アラートリソースデータの管理
フィードバック