Alibaba Cloud Log Service (SLS) Python SDK

repository·master·Indexed 41 days ago

https://github.com/aliyun/aliyun-log-python-sdk

A Python client library for programmatic access to Alibaba Cloud Log Service (SLS), compatible with Log Service API 0.6. It provides the LogClient for managing projects, logstores, and shards, as well as specialized logging handlers (SimpleLogHandler, QueuedLogHandler) for integrating standard Python logs. The SDK includes tools for Logtail configuration, data export via Shippers, Elasticsearch migration via MigrationManager, and high-throughput log consumption using Consumer Groups and ConsumerWorker.

Tokens
23.7K
Snippets
57
Records
83
Agent score
51%

What's inside Alibaba Cloud Log Service Python SDK

  1. Overview of aliyun-log-python-sdk features

    master

    The aliyun-log-python-sdk is an open-source Python interface for Alibaba Cloud Log Service (SLS) Rest APIs.

    Key capabilities include:

    • Full API Coverage: Encapsulates all Rest APIs for management, data operations, and consumer groups.
    • High-level Consumer Group Support: Advanced classes for managing consumer groups.
    • Python Logging Integration: Includes a Handler for the standard Python logging module.
    • High-level Operations: Supports automatic pagination, automatic retries for unfinished tasks, copying Project/Logstore configurations, adjusting Shard read/write counts, and resource usage monitoring.
    • Data Migration & ETL: Supports Elasticsearch data migration and high-speed data ETL (Extract, Transform, Load) across logstores based on shard or time, supporting concurrent batch or continuous transformations.
  2. Understand Elasticsearch to SLS data type mapping

    master

    MigrationManager automatically creates indices in the target SLS logstore based on Elasticsearch data types.

    Core Datatypes

    ElasticsearchSLS
    texttext
    keywordtext (non-tokenized)
    long, integer, short, bytelong
    double, float, half_float, scaled_floatdouble
    datetext
    booleantext (non-tokenized)
    integer_range, float_range, long_range, double_range, date_rangejson
    IPtext (non-tokenized)
    Geo-point, Geo-Shapetext

    Complex Datatypes

    ElasticsearchSLS
    Objectjson
    Arrayn/a
    Nestedn/a
  3. Customize KV parsing separators and field naming

    master

    The KV parser supports various configurations to handle different log formats and avoid naming collisions with built-in log fields.

    Custom Separators

    By default, the parser uses the equals sign (=) to separate keys and values. You can change this using the extract_kv_sep parameter. You can also provide a regular expression to support multiple separators (e.g., both = and :).

    Handling Field Name Collisions

    If your log keys (e.g., level) conflict with Aliyun Log Service's built-in fields, you can use prefixes or suffixes to differentiate them:

    • Use buildin_fields_prefix or buildin_fields_suffix to modify the built-in system fields.
    • Use extract_kv_prefix or extract_kv_suffix to modify the extracted KV fields.
  4. Real-time consumption with Consumer Groups

    master

    Consumer Groups provide a high-level, scalable, and reliable way to consume logs in real-time. While advanced integration patterns (like Splunk integration) are available via tutorials, you can manage consumer groups using these basic interfaces:

    • list_consumer_group: List current consumer groups.
    • create_consumer_group: Create a new consumer group.
    • update_consumer_group: Update settings like delay or consumption order.
    • delete_consumer_group: Delete a consumer group.
    • get_check_point: Retrieve the current consumption progress (Checkpoint).
    • update_check_point: Store and update the consumption progress to ensure reliable processing.
  5. Manage Shards and Cursors for Log Consumption

    master

    For advanced log consumption (e.g., building a custom consumer), you can manage the underlying storage structure and the position in the log stream.

    Shards: Control the scale of your logstore by using list_shards, split_shard (to increase throughput), and merge_shard (to reduce costs/complexity).

    Cursors: To track your position in a logstream for continuous reading, use cursor management methods:

    • get_cursor: Get a cursor for a specific time.
    • get_cursor_time: Get a cursor based on a timestamp.
    • get_previous_cursor_time: Retrieve the previous cursor time.
    • get_begin_cursor: Get the starting cursor.
    • get_end_cursor: Get the latest cursor.
  6. Customize collected log fields in QueuedLogHandler

    master

    By default, QueuedLogHandler collects all available log domains. You can restrict the collection to specific fields by passing a list of field names to the fields parameter. Note that the message field is always collected.

    Supported Log Domains

    DomainDescription
    messageLog message content (always collected)
    record_nameName of the logging handler
    levelLog level (e.g., INFO, ERROR)
    file_pathFull path to the code file
    func_nameFunction name
    line_noLine number
    moduleModule name
    thread_idCurrent thread ID
    thread_nameCurrent thread name
    process_idCurrent process ID
    process_nameCurrent process name

    Example: Restricting Fields

    In a logging.conf file, pass the list as an argument:

    [handler_slsHandler]
    class=aliyun.log.QueuedLogHandler
    level=INFO
    formatter=rawFormatter
    args=('cn-beijing.log.aliyuncs.com', 'ak_id', 'ak_key', 'project1', "logstore1", 'mytopic', ['level', 'func_name', 'module', 'line_no'])

    You can also use buildin_fields_prefix and buildin_fields_suffix to add prefixes or suffixes to these built-in domains (e.g., __level__).

  7. Monitor migration progress and logs in SLS

    master

    MigrationManager uses the Python logging module to record execution status. These logs are automatically uploaded to a special logstore named internal-es-migration-log within your target SLS project.

    To track a specific migration, find the migration ID (e.g., c34d9636f8934cc18b9727263c476b66) printed in the console and search for it in SLS using the tag __migration__.

    Key Log Fields:

    • total: Total number of tasks.
    • finished: Number of completed tasks.
    • failed: Number of failed tasks.
    • dropped: Number of dropped tasks.
    • checkpoint: Indicates the last processed _id and offset for a specific shard, used for resumption.
  8. How Consumer Groups and Consumers work together

    master

    The Consumer Library is a high-level mode for consuming logs in Alibaba Cloud Log Service (SLS). It abstracts the complexity of log consumption using two main concepts:

    • Consumer Group (ConsumerGroup): A collection of multiple consumers that collectively consume data from a single Logstore. Consumers within the same group do not consume duplicate data.
    • Consumer: The basic unit of a Consumer Group that performs the actual consumption task. Each consumer within a group must have a unique name.

    Shard Allocation Rules:

    • Each shard is assigned to exactly one consumer.
    • A single consumer can own multiple shards.
    • When a new consumer joins a group, shards are automatically rebalanced among consumers to ensure load balancing, a process that is transparent to the user.

    Checkpointing: The library automatically saves checkpoints (checkpoints) on the server side. This allows a program to resume consumption from the last saved position after a failure, ensuring data is not lost or unnecessarily re-processed.

  9. Enable automatic JSON parsing in QueuedLogHandler

    master

    The aliyun.log.QueuedLogHandler provides a feature to automatically parse JSON or KV formatted strings within log messages into searchable fields in Alibaba Cloud Log Service. This allows you to pass Python dictionaries directly to the logger, and the handler will extract the keys and values as individual log fields instead of treating the entire dictionary as a single string message.

    To enable this, you must set the extract_json parameter to True during configuration.

    # Example of passing a dictionary that will be parsed into fields
    response_data = {'name': '小明', 'score': 100.0}
    logger.info(response_data)
  10. What are Consumer Groups and Consumers in SLS

    master

    The Consumer Library is a high-level abstraction for consuming logs in Alibaba Cloud Log Service (SLS). It manages complexity such as load balancing, failover, and checkpointing automatically.

    • Consumer Group: A collection of multiple consumers that collectively consume data from a single logstore. Consumers within the same group do not process duplicate data.
    • Consumer: The basic unit of a Consumer Group that performs the actual data consumption tasks. Each consumer within a group must have a unique name.

    Shard Allocation Principles:

    • Each shard is assigned to exactly one consumer.
    • A single consumer can own multiple shards.
    • When a new consumer joins a group, shards are redistributed to balance the load, a process that is transparent to the user.

    Checkpointing: The library automatically saves checkpoints, allowing a program to resume consumption from the last successful position in case of failure, preventing data duplication.

  11. Consume logs via PullLog (Cursor-based)

    master

    Pulling logs using cursors is a way to consume data from specific shards. You must specify a shard_id and a cursor to track progress.

    Cursor Operations

    • Get beginning cursor: get_begin_cursor(project, logstore, shard_id)
    • Get end cursor: get_end_cursor(project, logstore, shard_id)
    • Get cursor at specific time: get_cursor(project, logstore, shard_id, start_time) (where start_time is the server acceptance time).
    • Get cursor time: Retrieve the server time associated with a cursor using get_cursor_time or the time of the previous cursor using get_previous_cursor_time.

    Pulling Data

    You can pull logs using several methods:

    1. pull_logs: Pulls logs based on a cursor.
    2. pull_log: An iterator-based approach using time ranges (from_time, to_time).
    3. pull_log_dump: Downloads logs directly to a local file path for high-concurrency scenarios.
    # Example: Pulling logs from a specific shard using a cursor
    from time import time
    res = client.get_cursor('project1', 'logstore1', shard_id=0, start_time=int(time())-3600)
    res = client.pull_logs('project1', 'logstore1', shard_id=0, cursor=res.get_cursor())
    res.log_print()
    
    # Example: Using the iterator approach
    it = client.pull_log('project1', 'logstore1', shard_id=0, from_time="2018-1-1 10:10:10", to_time="2018-1-1 10:20:10")
    for res in it:
        res.log_print()
    
    # Example: Dumping logs to a local file
    it = client.pull_log_dump('project1', 'logstore1', from_time="2018-1-1 10:10:10", to_time="2018-1-1 10:20:10", file_path="./data/dump_{}.data")