Tüm Ürünler
Search
Belge Merkezi

Simple Log Service:Python SDK ile hızlı başlangıç

Son Güncelleme:Sep 30, 2026

Simple Log Service Python SDK kullanarak bir proje ve Logstore oluşturun, günlük yazın ve günlükleri sorgulayın.

Ön koşullar

  • Gerekli izinlere sahip bir RAM kullanıcısı. RAM kullanıcısı oluşturma ve izin atama.

  • ALIBABA_CLOUD_ACCESS_KEY_ID ve ALIBABA_CLOUD_ACCESS_KEY_SECRET ortam değişkenlerini yapılandırın. Linux, macOS ve Windows üzerinde ortam değişkenlerini yapılandırma.

    Önemli

    Bir Alibaba Cloud hesabının AccessKey çifti, tüm API işlemleri için tam yetki sağlar. API çağrıları veya rutin işletim ve bakım işlemleri için bir RAM kullanıcısının AccessKey çiftini kullanın.

    AccessKey ID ve AccessKey Secret değerlerini proje kodunuzda sabit olarak kodlamayın. Kimlik bilgilerinin sabit kodlanması, istemeden ifşa edilmelerine ve hesabınızdaki tüm kaynakların güvenliğinin tehlikeye girmesine neden olabilir.

  • Simple Log Service Python SDK'yı yükleyin. Python için Simple Log Service SDK'yı yükleme.

Örnekler

  • Günlük toplamak için Python kodu yazma

    SLSQuickStart.py dosyasını oluşturun. Bu betik bir proje, Logstore ve dizin oluşturur, günlük yazar ve bir sorgu çalıştırır:

    from aliyun.log import LogClient, PutLogsRequest, LogItem, GetLogsRequest, IndexConfig
    import time
    import os
    
    # This example retrieves the AccessKey ID and AccessKey Secret from environment variables.
    accessKeyId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
    accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
    # The endpoint for Simple Log Service. This example uses the endpoint for the China (Hangzhou) region. Replace it with your 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 index configuration.
    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 time range for the query, in Unix timestamp format.
    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 an index.
    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)
    
    # 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 an index.
        create_index()
        # Write data to the Logstore.
        put_logs()
        # Query logs.
        get_logs()

    Örnek çıktı:

    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 GitHub deposunda daha fazla örnek bulunmaktadır.

  • Python günlüklerini toplamak için Logtail kullanma

    Python logging modülünden Logtail ile günlük toplayın. Python günlüklerini toplama.

İlgili konular