Tous les produits
Search
Centre de documentation

Simple Log Service:Consommer des données de journal à l'aide du SDK SLS pour Java

Dernière mise à jour :Aug 18, 2026

Le SDK SLS pour Java vous permet de consommer des données de journal en appelant l'opération PullLogs, avec ou sans filtrage SPL.

Prérequis

Contexte

L'opération PullLogs récupère les données de journal via un curseur. Pour plus d'informations, consultez PullLogs. Les applications Java, Python et Go peuvent consommer les données SLS en tant que consommateurs individuels ou groupes de consommateurs.

SLS prend en charge le langage SPL (Simple Log Service Processing Language) pour la consommation en temps réel, les requêtes basées sur l'analyse et la collecte via Logtail. Pour plus d'informations, consultez Syntaxe SPL.

Procédure

Installez le SDK SLS pour Java avant de poursuivre. Pour plus d'informations, consultez Installer le SDK Java.

Utiliser le SDK

L'exemple suivant appelle l'opération PullLogs pour consommer des données de journal. Pour plus d'informations, consultez PullLogs.

Paramètres

Paramètre

Type

Obligatoire

Description

project

string

Oui

Nom du projet. Pour plus d'informations, consultez Gérer les projets.

logStore

string

Oui

Nom du Logstore. Les Logstores collectent, stockent et interrogent les journaux. Pour plus d'informations, consultez Gérer les Logstores.

shardId

int

Oui

ID du shard dans le Logstore. Pour plus d'informations, consultez Shard.

Ajouter des dépendances Maven

Ouvrez le fichier pom.xml situé dans le répertoire racine de votre projet Java et ajoutez le code suivant :

<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.aliyun.openservices</groupId>
  <artifactId>aliyun-log</artifactId>
  <version>0.6.99</version>
</dependency>

Créer un fichier nommé PullLogsDemo.java

Exemple de code :

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Consts;
import com.aliyun.openservices.log.common.LogGroupData;
import com.aliyun.openservices.log.common.Shard;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.PullLogsRequest;
import com.aliyun.openservices.log.response.ListShardResponse;
import com.aliyun.openservices.log.response.PullLogsResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PullLogsDemo {
    // 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.
    private static final String endpoint = "cn-hangzhou.log.aliyuncs.com";
    // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // The name of the project.
    private static final String project = "your_project";
    // The name of the Logstore.
    private static final String logStore = "your_logstore";

    public static void main(String[] args) throws Exception {
        // Create a client for Simple Log Service.
        Client client = new Client(endpoint, accessKeyId, accessKeySecret);
        // Query the shards of the Logstore.
        ListShardResponse resp = client.ListShard(project, logStore);
        System.out.printf("%s has %d shards\n", logStore, resp.GetShards().size());
        Map<Integer, String> cursorMap = new HashMap<Integer, String>();
        for (Shard shard : resp.GetShards()) {
            int shardId = shard.getShardId();
            // Use the BEGIN cursor or obtain a specific cursor to consume log data. If you want to use the END cursor to consume log data, use Consts.CursorMode.END.
            cursorMap.put(shardId, client.GetCursor(project, logStore, shardId, Consts.CursorMode.BEGIN).GetCursor());
        }
        try {
            while (true) {
                // Obtain logs from each shard.
                for (Shard shard : resp.GetShards()) {
                    int shardId = shard.getShardId();
                    PullLogsRequest request = new PullLogsRequest(project, logStore, shardId, 1000, cursorMap.get(shardId));
                    PullLogsResponse response = client.pullLogs(request);
                    // Obtain logs from log groups by logic. Logs are usually stored in log groups. 
                    List<LogGroupData> logGroups = response.getLogGroups();
                    System.out.printf("Get %d logGroup from logStore:%s:\tShard:%d\n", logGroups.size(), logStore, shardId);
                    // Move the cursor after the obtained logs are processed. 
                    cursorMap.put(shardId, response.getNextCursor());
                }
            }
        } catch (LogException e) {
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Utiliser le SDK et SPL

L'exemple suivant appelle l'opération PullLogs pour une consommation de journaux basée sur SPL. Pour plus d'informations, consultez PullLogs.

Paramètres

Paramètre

Type

Obligatoire

Description

project

string

Oui

Nom du projet. Pour plus d'informations, consultez Gérer les projets.

logStore

string

Oui

Nom du Logstore. Les Logstores collectent, stockent et interrogent les journaux. Pour plus d'informations, consultez Gérer les Logstores.

shardId

int

Oui

ID du shard dans le Logstore. Pour plus d'informations, consultez Shard.

Ajouter des dépendances Maven

Ouvrez le fichier pom.xml situé dans le répertoire racine de votre projet Java et ajoutez le code suivant :

<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.aliyun.openservices</groupId>
  <artifactId>aliyun-log</artifactId>
  <version>0.6.99</version>
</dependency>

Créer un fichier nommé PullLogsWithSPLDemo.java

Exemple de code :

import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.*;
import com.aliyun.openservices.log.common.Consts;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.PullLogsRequest;
import com.aliyun.openservices.log.response.ListShardResponse;
import com.aliyun.openservices.log.response.PullLogsResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PullLogsWithSPLDemo {
    // 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.
    private static final String endpoint = "cn-hangzhou.log.aliyuncs.com";
    // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    private static final String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // The name of the project.
    private static final String project = "your_project";
    // The name of the Logstore.
    private static final String logStore = "your_logstore";

    public static void main(String[] args) throws Exception {
        // Create a client for Simple Log Service.
        Client client = new Client(endpoint, accessKeyId, accessKeySecret);
        // Query the shards of the Logstore.
        ListShardResponse resp = client.ListShard(project, logStore);
        System.out.printf("%s has %d shards\n", logStore, resp.GetShards().size());
        Map<Integer, String> cursorMap = new HashMap<Integer, String>();
        for (Shard shard : resp.GetShards()) {
            int shardId = shard.getShardId();
            // Use the BEGIN cursor or obtain a specific cursor to consume log data. If you want to use the END cursor to consume log data, use Consts.CursorMode.END.
            cursorMap.put(shardId, client.GetCursor(project, logStore, shardId, Consts.CursorMode.BEGIN).GetCursor());
        }
        try {
            while (true) {
                // Obtain logs from each shard.
                for (Shard shard : resp.GetShards()) {
                    int shardId = shard.getShardId();
                    PullLogsRequest request = new PullLogsRequest(project, logStore, shardId, 1000, cursorMap.get(shardId));
                    request.setQuery("* | where cast(body_bytes_sent as bigint) > 14000");
                    request.setPullMode("scan_on_stream");
                    PullLogsResponse response = client.pullLogs(request);
                    // Obtain logs from log groups by logic. Logs are usually stored in log groups. 
                    List<LogGroupData> logGroups = response.getLogGroups();
                    System.out.printf("Get %d logGroup from logStore:%s:\tShard:%d\n", logGroups.size(), logStore, shardId);

                    // Move the cursor after the obtained logs are processed. 
                    cursorMap.put(shardId, response.getNextCursor());
                }
            }
        } catch (LogException e) {
            System.out.println("error code :" + e.GetErrorCode());
            System.out.println("error message :" + e.GetErrorMessage());
            throw e;
        }
    }
}

Références