Todos los productos
Search
Centro de documentos

Simple Log Service:Get started with Simple Log Service SDK for Java

Última actualización: Sep 02, 2026

Utilice el SDK de Simple Log Service (SLS) para Java con el fin de crear un proyecto, un logstore y un índice; posteriormente, escriba y consulte datos de registro.

Requisitos previos

Antes de empezar, asegúrese de contar con lo siguiente:

  • Java Runtime Environment (JRE) 6.0 o posterior instalado. Ejecute java -version para comprobarlo. Si Java no está instalado, descárguelo desde el sitio web oficial de Java

  • El SDK de SLS para Java instalado. Para obtener instrucciones de instalación, consulte Install SLS SDK for Java

  • Un AccessKey ID y un AccessKey secret creados en Alibaba Cloud console, almacenados como variables de entorno:

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Paso 1: Inicializar el cliente

Todos los pasos de este tutorial comparten una única instancia de Client. El endpoint especifica qué región procesa sus solicitudes.

import com.aliyun.openservices.log.Client;

public class SlsQuickStart {
    // Obtain credentials from environment variables
    static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    // SLS endpoint for China (Hangzhou). Replace with your region endpoint.
    static String host = "cn-hangzhou.log.aliyuncs.com";

    static Client client = new Client(host, accessId, accessKey);
}

Reemplace cn-hangzhou.log.aliyuncs.com por el endpoint correspondiente a su región. El formato del endpoint es <region-id>.log.aliyuncs.com.

Paso 2: Crear un proyecto

Un proyecto es el contenedor de recursos de nivel superior en SLS. Los logstores, índices y paneles pertenecen a un proyecto.

static String projectName = "aliyun-test-gs-project";

static void createProject() throws LogException, InterruptedException {
    String projectDescription = "project description";
    System.out.println("ready to create project");
    client.CreateProject(projectName, projectDescription);
    System.out.println(String.format("create project %s success", projectName));
    // Wait for the project to become fully available after creation
    TimeUnit.SECONDS.sleep(60 * 2);
}
La espera de 2 minutos considera el tiempo necesario para que el proyecto esté completamente disponible. En entornos de producción, utilice lógica de sondeo o reintentos en lugar de una pausa fija.

Paso 3: Crear un logstore

Un logstore recopila, almacena y permite consultar datos de registro dentro de un proyecto. Configure su periodo de retención y la cantidad de shards según su carga de trabajo.

static String logstoreName = "aliyun-test-logstore";

static void createLogstore() throws LogException, InterruptedException {
    System.out.println("ready to create logstore");
    int ttlInDay = 3;     // Data retention period in days. Set to 3650 for permanent storage.
    int shardCount = 2;   // Number of shards for read/write throughput
    LogStore store = new LogStore(logstoreName, ttlInDay, shardCount);
    client.CreateLogStore(projectName, store);
    System.out.println(String.format("create logstore %s success", logstoreName));
    // Wait for the logstore to become available
    TimeUnit.SECONDS.sleep(60);
}

Parámetro

Descripción

Ejemplo

ttlInDay

Periodo de retención de datos en días. Establezca este valor en 3650 para almacenamiento permanente.

3

shardCount

Cantidad de shards. Un mayor número de shards incrementa el rendimiento de lectura y escritura.

2

Paso 4: Crear un índice

Un índice habilita la búsqueda y el análisis de registros en un logstore. Este ejemplo crea un índice de texto completo e índices de campo para los campos dev e id.

static void createIndex() throws LogException, InterruptedException {
    System.out.println(String.format("ready to create index for %s", logstoreName));
    // Index configuration:
    // - Full-text index with standard tokenizers (comma, space, quotes, brackets, etc.)
    // - Field index on "dev" (text type) and "id" (long type)
    // - Case-insensitive, Chinese tokenization disabled, max text length 2048
    String logstoreIndex = "{\"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}";
    Index index = new Index();
    index.FromJsonString(logstoreIndex);
    client.CreateIndex(projectName, logstoreName, index);
    System.out.println(String.format("create index for %s success", logstoreName));
    // Wait for the index to become available
    TimeUnit.SECONDS.sleep(60);
}

La configuración JSON del índice establece los siguientes parámetros:

Configuración

Valor

Descripción

Tokens del índice de texto completo

, '";=()[]{}?@&<>/:\n\t\r

Delimitadores para la tokenización del texto de registro

caseSensitive

false

Búsqueda sin distinción entre mayúsculas y minúsculas

chn

false

Tokenización de chino deshabilitada

Campo dev

text

Campo de texto con análisis habilitado (doc_value: true)

Campo id

long

Campo numérico con análisis habilitado (doc_value: true)

max_text_len

2048

Longitud máxima de texto para indexación

Paso 5: Escribir datos de registro

Escriba 100 eventos de registro de ejemplo en el logstore. Cada evento contiene un campo id y un campo dev.

static void pushLogs() throws LogException, InterruptedException {
    System.out.println(String.format("ready to push logs for %s", logstoreName));
    List<LogItem> logGroup = new ArrayList<LogItem>();
    for (int i = 0; i < 100; ++i) {
        LogItem logItem = new LogItem();
        logItem.PushBack("id", String.valueOf(i));
        logItem.PushBack("dev", "test_push");
        logGroup.add(logItem);
    }
    client.PutLogs(projectName, logstoreName, "", logGroup, "");
    System.out.println(String.format("push logs for %s success", logstoreName));
    // Brief wait for logs to be indexed
    TimeUnit.SECONDS.sleep(5);
}
PutLogs es adecuado para escenarios de bajo volumen. Para cargas de trabajo con alto rendimiento o alta concurrencia, utilice Alibaba Cloud Log Java Producer , que ofrece procesamiento por lotes, reintentos y envío asíncrono.

Paso 6: Consultar registros

Ejecute una consulta SQL para recuperar eventos de registro del logstore dentro de una ventana de una hora.

static String query = "*| select * from " + logstoreName;

static void queryLogs() throws LogException {
    System.out.println(String.format("ready to query logs from %s", logstoreName));
    // Query the last hour. fromTime and toTime are UNIX timestamps in seconds.
    int fromTime = (int) (System.currentTimeMillis() / 1000 - 3600);
    int toTime = fromTime + 3600;
    GetLogsResponse getLogsResponse = client.GetLogs(projectName, logstoreName, fromTime, toTime, "", query);
    for (QueriedLog log : getLogsResponse.getLogs()) {
        for (LogContent mContent : log.mLogItem.mContents) {
            System.out.println(mContent.mKey + " : " + mContent.mValue);
        }
        System.out.println("********************");
    }
}

Código completo

A continuación se presenta un ejemplo que combina todos los pasos anteriores en un solo programa ejecutable. Cree un archivo llamado SlsQuickStart.java y pegue el siguiente código.

import com.aliyun.openservices.log.common.Index;
import com.aliyun.openservices.log.common.LogContent;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.common.LogStore;
import com.aliyun.openservices.log.common.QueriedLog;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.GetLogsResponse;
import com.aliyun.openservices.log.Client;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SlsQuickStart {
    // Obtain credentials from environment variables
    static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    // SLS endpoint for China (Hangzhou). Replace with your region endpoint.
    static String host = "cn-hangzhou.log.aliyuncs.com";

    static Client client = new Client(host, accessId, accessKey);

    static String projectName = "aliyun-test-gs-project";
    static String logstoreName = "aliyun-test-logstore";
    static String query = "*| select * from " + logstoreName;

    static void createProject() throws LogException, InterruptedException {
        String projectDescription = "project description";
        System.out.println("ready to create project");
        client.CreateProject(projectName, projectDescription);
        System.out.println(String.format("create project %s success", projectName));
        TimeUnit.SECONDS.sleep(60 * 2);
    }

    static void createLogstore() throws LogException, InterruptedException {
        System.out.println("ready to create logstore");
        int ttlInDay = 3;
        int shardCount = 2;
        LogStore store = new LogStore(logstoreName, ttlInDay, shardCount);
        client.CreateLogStore(projectName, store);
        System.out.println(String.format("create logstore %s success", logstoreName));
        TimeUnit.SECONDS.sleep(60);
    }

    static void createIndex() throws LogException, InterruptedException {
        System.out.println(String.format("ready to create index for %s", logstoreName));
        String logstoreIndex = "{\"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}";
        Index index = new Index();
        index.FromJsonString(logstoreIndex);
        client.CreateIndex(projectName, logstoreName, index);
        System.out.println(String.format("create index for %s success", logstoreName));
        TimeUnit.SECONDS.sleep(60);
    }

    static void pushLogs() throws LogException, InterruptedException {
        System.out.println(String.format("ready to push logs for %s", logstoreName));
        List<LogItem> logGroup = new ArrayList<LogItem>();
        for (int i = 0; i < 100; ++i) {
            LogItem logItem = new LogItem();
            logItem.PushBack("id", String.valueOf(i));
            logItem.PushBack("dev", "test_push");
            logGroup.add(logItem);
        }
        client.PutLogs(projectName, logstoreName, "", logGroup, "");
        System.out.println(String.format("push logs for %s success", logstoreName));
        TimeUnit.SECONDS.sleep(5);
    }

    static void queryLogs() throws LogException {
        System.out.println(String.format("ready to query logs from %s", logstoreName));
        int fromTime = (int) (System.currentTimeMillis() / 1000 - 3600);
        int toTime = fromTime + 3600;
        GetLogsResponse getLogsResponse = client.GetLogs(projectName, logstoreName, fromTime, toTime, "", query);
        for (QueriedLog log : getLogsResponse.getLogs()) {
            for (LogContent mContent : log.mLogItem.mContents) {
                System.out.println(mContent.mKey + " : " + mContent.mValue);
            }
            System.out.println("********************");
        }
    }

    public static void main(String[] args) throws LogException, InterruptedException {
        createProject();
        createLogstore();
        createIndex();
        pushLogs();
        queryLogs();
    }
}

Salida esperada

Después de ejecutar SlsQuickStart.java, la consola muestra lo siguiente:

ready to create project
create project aliyun-test-gs-project success
ready to create logstore
create logstore aliyun-test-logstore success
ready to create index for aliyun-test-logstore
create index for aliyun-test-logstore success
ready to push logs for aliyun-test-logstore
push logs for aliyun-test-logstore success
ready to query logs from aliyun-test-logstore
dev : test_push
id : 0
********************
dev : test_push
id : 1
********************
dev : test_push
id : 2
********************
...
La salida real de la consulta también puede incluir campos de metadatos del sistema, como __line__ , __topic__ y __time___0 .

Referencias