All Products
Search
Document Center

Simple Log Service:Soft deletion in Simple Log Service

Last Updated:Dec 01, 2025

Alibaba Cloud Simple Log Service (SLS) supports soft deletion. This feature lets you mark log data as deleted instead of permanently removing it. This topic describes how to perform a soft deletion.

Important

The soft deletion feature for Simple Log Service is in grayscale release and is available to specific users in specific regions. To enable this feature, submit a ticket.

Background information

In a data-driven environment, logs and observable data are key business assets. However, they also present challenges in data management, compliance, and security. To address these issues, Alibaba Cloud Simple Log Service (SLS) offers the soft deletion feature. This feature provides a traceable deletion mechanism and serves as a safety net for your data security and compliance system.

How it works (click to view)

Soft deletion marks data for deletion instead of permanently deleting it. The soft deletion mechanism balances logical deletion with physical presence. The workflow is as follows:

  1. Initiate a deletion task: Use the software development kit (SDK) or the console to start an asynchronous deletion task. Specify a time range and query conditions.

  2. Precise marking: The SLS backend service locates all matching log entries based on your query conditions. Instead of physically erasing the data, the service adds an internal, invisible delete marker to each entry.

  3. Query transparency: After data is marked, all regular query requests, such as GetLogs, GetHistograms, and SQL analysis, automatically filter out this data. To applications and users, this data appears to be deleted.

  4. Retention and restoration: The marked data is physically stored for a preset retention period, such as 1 to 365 days. Data restoration is not currently supported.

  5. Permanent deletion: After the retention period expires, the SLS recovery mechanism performs an irreversible physical deletion of the data to release storage space.

Scenarios (click to view)

The soft deletion feature of Alibaba Cloud Simple Log Service (SLS) addresses the following core data management challenges by marking data for deletion instead of immediately and permanently removing it:

  • Compliance and audit requirements

    • Scenario: Regulations, such as financial supervision or GDPR, require businesses to be able to delete data on demand and keep audit records of deletion operations.

    • Implementation: Soft deletion operations generate system logs that record the deletion time, operator, and data scope to meet audit compliance requirements.

  • Data management in development and test environments

    • Scenario: The testing team needs to regularly clean up old test data to prepare for new stress testing.

    • Implementation: You can perform batch soft deletions of specified data. This retains the Logstore structure and configuration, which avoids the rebuilding costs associated with physical deletion.

  • Dirty data cleanup

    • Scenario: An online failure causes the collection of abnormal data, which affects analysis accuracy.

    • Implementation: Quickly isolate and mark dirty data to ensure that business views contain only high-quality data. The raw data is retained for later troubleshooting.

This feature works with SLS security and compliance capabilities, such as server-side encryption and fine-grained permission control, to meet enterprise-level data governance needs.

Precautions

  1. Storage cost considerations: Soft-deleted data still occupies storage space and incurs fees during the retention period. The data is not physically deleted until the retention period ends.

  2. Query statement accuracy: Query before you delete. Before you perform a deletion, run a query using the exact same query time and search statement. Preview the data that will be deleted to confirm that the data is correct before you proceed with the deletion.

  3. You cannot query or analyze soft-deleted logs. This includes queries, SQL analysis, ScheduledSQL, and alerting. Stream processing operations are not affected. This includes consumption, data transformation, and delivery.

  4. Soft deletion is irreversible. Deleted logs cannot be recovered.

Supported regions

Soft deletion is currently supported in Singapore and China (Ulanqab). You can view the endpoint for the region where your project is located on the project's overview page. For more information about the region IDs, see Endpoints.

Permissions

  • If you log on with an Alibaba Cloud account, you have all operation permissions by default and can perform operations on the project directly.

  • If you log on with a Resource Access Management (RAM) user, you must request the required permissions from the Alibaba Cloud account owner. Simple Log Service provides the following system policies:

    • System policies: These policies grant broad permissions. Users cannot modify the content of system policies, but the configuration steps are simple.

      • AliyunLogFullAccess: Grants full management permissions on Simple Log Service.

      • AliyunLogReadOnlyAccess: Grants read-only permissions on Simple Log Service.

    • Custom policies: Follow the principle of least privilege. Grant only the minimum required permissions to trusted personnel or automated services.

      The following code provides a sample custom policy:

      {
        "Version": "1",
        "Statement": [
          {
            "Action": [
              "log:DeleteLogStoreLogs",
              "log:GetDeleteLogStoreLogsTask",
              "log:ListDeleteLogStoreLogsTasks",
            ],
            "Resource": [
              "acs:log:*:*:project/ProjectName/logstore/LogStoreName"
            ]
            "Effect": "Allow"
          }
        ]
      }

Console operations

  1. Log on to the Simple Log Service console. In the Projects section, click the one you want.

  2. On the Log Storage > Logstores tab, click the logstore you want.

  3. On the Search & Analysis page of the Logstore, enter a search statement and specify a time range. On the Raw Logs tab, click image > Soft Delete Log.

    image

  4. In the Soft Delete Log dialog box, carefully read the information and click Confirm. After the deletion is complete, the logs are no longer visible.

  5. After the deletion is complete, on the Raw Logs tab, click image > Soft Delete Task. In the Soft Delete Task list, you can view the history of deletion tasks.

SDK operations

Python

  1. Run pip show aliyun-log-python-sdk to check the version of aliyun-log-python-sdk.

    The version of aliyun-log-python-sdk must be 0.9.28 or later. If the version is earlier, run pip install -U aliyun-log-python-sdk to upgrade the SDK.

  2. Submit a soft deletion task.

    The following table describes the parameters of DeleteLogsRequest.

    Parameter

    Example

    # Import necessary libraries
    import time
    from aliyun.log import LogClient, DeleteLogsRequest, DeleteLogsResponse
    
    def execute_soft_delete(client: LogClient, project: str, logstore: str, from_time: int, to_time: int, query: str) -> str:
        """
        Executes an asynchronous soft deletion task.
    
        :param client: An initialized SLS client instance.
        :param project: Your SLS project name.
        :param logstore: Your Logstore name.
        :param from_time: The start timestamp of the deletion range (in seconds).
        :param to_time: The end timestamp of the deletion range (in seconds).
        :param query: The index-only search statement used to filter logs for deletion (SQL, scan, and phrase queries are not supported).
        :return: The task ID of the asynchronous deletion task, used to query the task status later.
        """
        print(f"Preparing to perform a soft deletion in Logstore '{logstore}' of project '{project}'...")
        print(f"Time range: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(from_time))} -> {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(to_time))}")
        print(f"Deletion condition (Query): {query}")
    
        # 1. Construct the deletion request object
        request = DeleteLogsRequest(project, logstore, from_time, to_time, query=query)
    
        # 2. Initiate the asynchronous deletion request
        try:
            res: DeleteLogsResponse = client.delete_logs(request)
            
            # 3. Print the request information and the returned task ID
            print("\n--- Request Receipt ---")
            res.log_print()
            task_id = res.get_taskid()
            print(f"✅ Soft deletion task submitted successfully! Request ID: {res.get_request_id()}, Task ID: {task_id}")
            return task_id
        except Exception as e:
            print(f"❌ Failed to submit soft deletion task: {e}")
            return ""
    
    # --- How to call ---
    # client = LogClient(...) # Client initialization process is omitted here
    
    # project_name = "my-prod-app"
    # logstore_name = "nginx-access-log"
    # # Scenario: Delete access logs from the last 24 hours with a status code of 500 from a specific IP address
    # start_time = int(time.time()) - 86400 
    # end_time = int(time.time())
    # delete_query = "__source__: 123.123.XXX.XXX and status: 500"
    
    # task_id = execute_soft_delete(client, project_name, logstore_name, start_time, end_time, delete_query)
    # if task_id:
    #     print(f"\nPlease use Task ID '{task_id}' to query the task execution status.")
    

    project String (Required)

    The name of the project. The project in Simple Log Service is used to isolate the resources of different users and control access to specific resources. See Manage projects.

    logstore String (Required)

    The name of the logstore. The logstore in Simple Log Service is used to collect, store, and query logs. See Manage a logstore.

    fromTime int (Required)

    The beginning of the time range to query. Specify the time as a UNIX timestamp.

    toTime int (Required)

    The end of the time range to query. Specify the time as a UNIX timestamp.

    query String (Required)

    The search statement or analytic statement. For more information, see Query and analysis overview.

    Use caution when you set the query to "*" or "level: ERROR". This may cause a large amount of data to be unexpectedly deleted.
  3. Poll the task status.

    This code block continuously checks the task progress until the task is complete or times out. This is a key step to ensure that the deletion operation is successfully executed.

    delete_logs is an asynchronous API. A successful call indicates only that the task is accepted. You must use the returned task_id to poll the final status of the task.

    from aliyun.log import GetDeleteLogsStatusRequest, GetDeleteLogsStatusResponse
    
    def wait_for_task_completion(client: LogClient, project: str, logstore: str, task_id: str, timeout_seconds: int = 300):
        """Waits for the soft deletion task to complete by polling."""
        start_time = time.time()
        while time.time() - start_time < timeout_seconds:
            request = GetDeleteLogsStatusRequest(project, logstore, task_id)
            try:
                res: GetDeleteLogsStatusResponse = client.get_delete_logs_status(request)
                progress = res.get_process()
                print(f"Querying status of task '{task_id}'... Progress: {progress:.2f}%")
                if progress >= 100.0:
                    print("✅ Task completed!")
                    return True
                time.sleep(2)  # Avoid polling too frequently
            except Exception as e:
                print(f"❌ Failed to query task status: {e}")
                return False
        print(f"⌛️ Task timed out (exceeded {timeout_seconds} seconds). Please retry later or check the task status.")
        return False
    
    # --- How to call ---
    # task_id = execute_soft_delete(...)
    # if task_id:
    #     wait_for_task_completion(client, project_name, logstore_name, task_id)
    
  4. Audit and manage deletion tasks (view historical tasks).

    This feature is crucial for security audits and operations management because it provides a complete history of all deletion operations.
    from aliyun.log import ListDeleteLogsTasksRequest
    
    def list_all_delete_tasks(client: LogClient, project: str, logstore: str):
        """Lists the history of all soft deletion tasks for a specified Logstore."""
        print(f"\nListing the history of soft deletion tasks for Logstore '{logstore}' in project '{project}'...")
        request = ListDeleteLogsTasksRequest(project=project, logstore=logstore)
        try:
            res = client.list_delete_logs_tasks(request)
            print("✅ Task list retrieved successfully!")
            res.log_print() # log_print() prints all task details in a readable format
        except Exception as e:
            print(f"❌ Failed to retrieve task list: {e}")