Aliyun Log Service Python SDK

0.9.45 · active · verified Thu Apr 16

The Aliyun Log Service Python SDK provides a client library for interacting with Alibaba Cloud's Log Service. It allows users to collect, consume, query, and process logs. The current version is 0.9.45, and it generally follows a continuous release cadence with frequent bug fixes and feature additions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the LogClient and put a single log item to an Aliyun Log Service logstore. Ensure you replace placeholder values with your actual project, logstore, endpoint, and credentials, preferably loaded from environment variables.

import os
from aliyun.log import LogClient, LogItem, PutLogsRequest
import time

# Replace with your actual Aliyun Log Service details
endpoint = os.environ.get('ALIYUN_LOG_ENDPOINT', 'https://cn-hangzhou.log.aliyuncs.com') # e.g., 'cn-hangzhou.log.aliyuncs.com'
accesskey_id = os.environ.get('ALIYUN_AK_ID', '')
accesskey_secret = os.environ.get('ALIYUN_AK_SECRET', '')
project_name = os.environ.get('ALIYUN_LOG_PROJECT', 'your-project-name')
logstore_name = os.environ.get('ALIYUN_LOG_LOGSTORE', 'your-logstore-name')

if not all([accesskey_id, accesskey_secret]):
    print("Please set ALIYUN_AK_ID and ALIYUN_AK_SECRET environment variables.")
else:
    client = LogClient(endpoint, accesskey_id, accesskey_secret)

    # Create a log item
    log_item = LogItem()
    log_item.set_time(int(time.time()))
    log_item.set_contents([('level', 'INFO'), ('message', 'Hello from Python SDK'), ('source', 'quickstart')])

    # Put logs into a list
    log_items = [log_item]

    # Create a PutLogsRequest
    request = PutLogsRequest(
        project_name, 
        logstore_name, 
        'your-topic', 
        'your-source-ip', # Or use client.get_source_ip() if needed
        log_items
    )

    try:
        response = client.put_logs(request)
        print(f"PutLogs successful. Request ID: {response.get_request_id()}")
    except Exception as e:
        print(f"Failed to put logs: {e}")

view raw JSON →