すべてのプロダクト
Search
ドキュメントセンター

Simple Log Service:Python用のSimple Log Service SDKの使用を開始する

最終更新日:Sep 04, 2024

このトピックでは、Simple Log Service SDK for Pythonの使用を開始し、一般的な操作を実行する方法について説明します。 たとえば、プロジェクトの作成、Logstoreの作成、ログの書き込み、ログの照会ができます。

前提条件

  • RAM (Resource Access Management) ユーザーが作成され、必要な権限がRAMユーザーに付与されます。 詳細については、「RAMユーザーの作成とRAMユーザーへの権限付与」をご参照ください。

  • ALIBABA_CLOUD_ACCESS_KEY_IDおよびALIBABA_CLOUD_ACCESS_KEY_SECRET環境変数が設定されています。 詳細については、「環境変数の設定」をご参照ください。

    重要
    • Alibaba CloudアカウントのAccessKeyペアには、すべてのAPI操作に対する権限があります。 RAMユーザーのAccessKeyペアを使用して、API操作を呼び出したり、ルーチンのO&Mを実行したりすることを推奨します。

    • プロジェクトコードにAccessKey IDまたはAccessKey secretを保存しないことを推奨します。 そうしないと、AccessKeyペアが漏洩し、アカウント内のすべてのリソースのセキュリティが侵害される可能性があります。

  • Python用のSimple Log Service SDKがインストールされています。 詳細については、「Simple Log Service SDK For Pythonのインストール」をご参照ください。

  • ログを収集するためのPythonコードの記述

    この例では、SLSQuickStart.pyファイルが作成されます。 このファイルのサンプルコードでは、API操作を呼び出してプロジェクトを作成し、Logstoreを作成し、インデックスを作成し、ログを書き込み、ログを照会する方法の例を示します。 サンプルコード:

    aliyun.logインポートからの

    from aliyun.log import LogClient, PutLogsRequest, LogItem, GetLogsRequest, IndexConfig
    import time
    import os
    
    # Configure environment variables. In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
    # The Simple Log Service endpoint. In this example, the Simple Log Service endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint. 
    endpoint = "cn-hangzhou.log.aliyuncs.com" 
    
    # Create a Simple Log Service client.  
    client = LogClient(endpoint, accessKeyId, accessKey)
    
    # The name of the project. 
    project_name = "aliyun-test-project"
    # The name of the Logstore.
    logstore_name = "aliyun-test-logstore"
    # The query statement. 
    query = "*| select dev,id from " + logstore_name
    # The indexes. 
    logstore_index = {'line': {
        'token': [',', ' ', "'", '"', ';', '=', '(', ')', '[', ']', '{', '}', '?', '@', '&', '<', '>', '/', ':', '\n', '\t',
                  '\r'], 'caseSensitive': False, 'chn': False}, 'keys': {'dev': {'type': 'text',
                                                                                 'token': [',', ' ', "'", '"', ';', '=',
                                                                                           '(', ')', '[', ']', '{', '}',
                                                                                           '?', '@', '&', '<', '>', '/',
                                                                                           ':', '\n', '\t', '\r'],
                                                                                 'caseSensitive': False, 'alias': '',
                                                                                 'doc_value': True, 'chn': False},
                                                                         'id': {'type': 'long', 'alias': '',
                                                                                'doc_value': True}}, 'log_reduce': False,
        'max_text_len': 2048}
    
    # The from_time and to_time parameters specify the start time and end time of the time range within which you want to query logs. The values of the parameters are UNIX timestamps. 
    from_time = int(time.time()) - 3600
    to_time = time.time() + 3600
    
    # Create a project. 
    def create_project():
        print("ready to create project %s" % project_name)
        client.create_project(project_name, project_des="")
        print("create project %s success " % project_name)
        time.sleep(60)
    
    # Create a Logstore. 
    def create_logstore():
        print("ready to create logstore %s" % logstore_name)
        client.create_logstore(project_name, logstore_name, ttl=3, shard_count=2)
        print("create logstore %s success " % project_name)
        time.sleep(30)
    
    # Create indexes. 
    def create_index():
        print("ready to create index for %s" % logstore_name)
        index_config = IndexConfig()
        index_config.from_json(logstore_index)
        client.create_index(project_name, logstore_name, index_config)
        print("create index for %s success " % logstore_name)
        time.sleep(60 * 2)
    
    # Write data to the Logstore. 
    def put_logs():
        print("ready to put logs for %s" % logstore_name)
        log_group = []
        for i in range(0, 100):
            log_item = LogItem()
            contents = [
                ('dev', 'test_put'),
                ('id', str(i))
            ]
            log_item.set_contents(contents)
            log_group.append(log_item)
        request = PutLogsRequest(project_name, logstore_name, "", "", log_group, compress=False)
        client.put_logs(request)
        print("put logs for %s success " % logstore_name)
        time.sleep(60)
    
    
    # Execute an SQL statement to query logs. 
    def get_logs():
        print("ready to query logs from logstore %s" % logstore_name)
        request = GetLogsRequest(project_name, logstore_name, from_time, to_time, query=query)
        response = client.get_logs(request)
        for log in response.get_logs():
            for k, v in log.contents.items():
                print("%s : %s" % (k, v))
            print("*********************")
    
    
    if __name__ == '__main__':
        # Create a project. 
        create_project()
        # Create a Logstore. 
        create_logstore()
        # Create indexes. 
        create_index()
        # Write data to the Logstore. 
        put_logs()
        # Execute an SQL statement to query logs. 
        get_logs()

    応答:

    ready to create project aliyun-test-project
    create project aliyun-test-project success
    ready to create logstore aliyun-test-logstore
    create logstore aliyun-test-project success
    ready to create index for aliyun-test-logstore
    create index for aliyun-test-logstore success
    ready to put logs for aliyun-test-logstore
    put logs for aliyun-test-logstore success
    ready to query logs from logstore aliyun-test-logstore
    dev : test_put
    id : 0
    *********************
    dev : test_put
    id : 1
    *********************
    dev : test_put
    id : 2
    *********************
    dev : test_put
    id : 3
    *********************
    ........

    サンプルコードの詳細については、「aliyun-log-python-sdk」をご参照ください。

  • Logtailを使用してPythonログを収集する

    Logtailを使用して、PythonのログモジュールからPythonログを収集できます。 詳細については、「Pythonログの収集」をご参照ください。

関連ドキュメント

  • APIを呼び出した後、Log Serviceによって返された応答にエラー情報が含まれている場合、呼び出しは失敗します。 API呼び出しが失敗したときに返されるエラーコードに基づいてエラーを処理できます。 詳細については、エラーコードをご参照ください。

  • Alibaba Cloud OpenAPI Explorerは、デバッグ機能、SDK、サンプル、および関連ドキュメントを提供します。 OpenAPI Explorerを使用して、リクエストを手動でカプセル化したり署名したりすることなく、Log Service API操作をデバッグできます。 詳細については、をご覧ください。 OpenAPIポータル

  • Log Serviceは、Log Serviceの自動設定の要件を満たすコマンドラインインターフェイス (CLI) を提供します。 詳細については、「Log Service CLI」をご参照ください。

  • サンプルコードの詳細については、GitHubの「Alibaba Cloud Simple Log Service SDK For Python」をご参照ください。