Tüm Ürünler
Search
Belge Merkezi

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

Son Güncelleme:Sep 30, 2026

Java için Simple Log Service (SLS) SDK kullanarak bir proje, logstore ve dizin oluşturun; ardından günlük verilerini yazıp sorgulayın.

Ön koşullar

Başlamadan önce aşağıdaki gereksinimleri karşıladığınızdan emin olun:

  • Java Runtime Environment (JRE) 6.0 veya üzeri yüklü olmalıdır. Yüklemeyi doğrulamak için java -version komutunu çalıştırın. Java kurulu değilse Java resmi web sitesinden indirin.

  • Java için SLS SDK yüklenmiş olmalıdır. Kurulum talimatları için Java için SLS SDK yükleme konusuna bakın.

  • Alibaba Cloud konsolunda bir AccessKey ID ve AccessKey secret oluşturulmuş ve bunlar ortam değişkenleri olarak kaydedilmiş olmalıdır:

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

Adım 1: İstemciyi başlatın

Bu kılavuzdaki tüm adımlar tek bir Client örneğini paylaşır. Uç nokta, isteklerinizi hangi bölgenin işleyeceğini belirler.

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);
}

cn-hangzhou.log.aliyuncs.com değerini kendi bölgenizin uç noktasıyla değiştirin. Uç nokta biçimi <region-id>.log.aliyuncs.com şeklindedir.

Adım 2: Proje oluşturun

Proje, SLS'deki üst düzey kaynak kapsayıcısıdır. Logstore'lar, dizinler ve panolar bir projeye aittir.

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);
}
2 dakikalık bekleme süresi, projenin tamamen kullanılabilir hale gelmesi için gereken zamanı dikkate alır. Üretim ortamlarında sabit bir uyku süresi yerine polling veya yeniden deneme mantığı kullanın.

Adım 3: Logstore oluşturun

Logstore, bir proje içindeki günlük verilerini toplar, depolar ve sorgular. İş yükünüze uygun olacak şekilde saklama süresini ve parça sayısını yapılandırın.

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);
}


Parametre


Açıklama


Örnek


ttlInDay


Gün cinsinden veri saklama süresi. Kalıcı depolama için 3650 olarak ayarlayın.


3


shardCount


Parça sayısı. Daha fazla parça okuma/yazma aktarım hızını artırır.


2

Adım 4: Dizin oluşturun

Dizin, bir logstore üzerinde günlük araması ve analitiği yapmanızı sağlar. Bu örnek, tam metin dizini ile birlikte dev ve id alanları için alan dizinleri oluşturur.

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);
}

Dizin JSON yapılandırması aşağıdaki ayarları içerir:


Ayar


Değer


Açıklama


Tam metin dizini belirteçleri


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


Günlük metnini belirteçlere ayırmak için kullanılan sınırlayıcılar


caseSensitive


false


Büyük/küçük harfe duyarlı olmayan arama


chn


false


Çince belirteçleştirme devre dışı


dev alanı


text


Analitik etkinleştirilmiş metin alanı (doc_value: true)


id alanı


long


Analitik etkinleştirilmiş sayısal alan (doc_value: true)


max_text_len


2048


Dizinleme için maksimum metin uzunluğu

Adım 5: Günlük verisi yazın

Logstore'a 100 adet örnek günlük olayı yazın. Her günlük olayı bir id ve bir dev alanı içerir.

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 , düşük hacimli senaryolar için uygundur. Yüksek aktarım hızı veya yüksek eşzamanlılık gerektiren iş yükleri için toplu işleme, yeniden deneme ve zaman uyumsuz gönderim sağlayan Alibaba Cloud Log Java Producer kullanın.

Adım 6: Günlükleri sorgulayın

Bir saatlik zaman aralığında logstore'dan günlük olaylarını almak için bir SQL sorgusu çalıştırın.

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("********************");
    }
}

Tam kod

Aşağıdaki örnek, önceki tüm adımları tek bir çalıştırılabilir programda birleştirir. SlsQuickStart.java adlı bir dosya oluşturun ve aşağıdaki kodu yapıştırın.

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();
    }
}

Beklenen çıktı

SlsQuickStart.java dosyasını çalıştırdığınızda konsol şu çıktıyı verir:

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
********************
...
Gerçek sorgu çıktısı, __line__ , __topic__ ve __time___0 gibi sistem meta veri alanlarını da içerebilir.

İlgili kaynaklar