All Products
Search
Document Center

Simple Log Service:Memulai dengan SDK Simple Log Service untuk Java

Last Updated:Feb 28, 2026

Buat proyek, penyimpanan log, dan indeks, lalu tulis dan kueri log menggunakan SDK Simple Log Service (SLS) untuk Java.

Prasyarat

Sebelum memulai, pastikan Anda telah:

  • Menginstal Java Runtime Environment (JRE) 6.0 atau versi yang lebih baru. Jalankan java -version untuk memverifikasi versi Anda. Jika Java belum terinstal, unduh dari situs web resmi Java.

  • Menginstal SDK SLS untuk Java. Untuk petunjuknya, lihat Instal SDK SLS untuk Java.

  • ID AccessKey dan Rahasia AccessKey yang dibuat di Konsol Alibaba Cloud disimpan sebagai Variabel lingkungan:

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

Langkah 1: Inisialisasi client

Semua operasi dalam tutorial ini menggunakan instance Client yang sama. Titik akhir menentukan wilayah yang menangani permintaan Anda.

import com.aliyun.openservices.log.Client;

public class SlsQuickStart {
    // Dapatkan kredensial dari variabel lingkungan
    static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    // Titik akhir SLS untuk China (Hangzhou). Ganti dengan titik akhir wilayah Anda.
    static String host = "cn-hangzhou.log.aliyuncs.com";

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

Ganti cn-hangzhou.log.aliyuncs.com dengan titik akhir wilayah Anda. Format titik akhir adalah <region-id>.log.aliyuncs.com.

Langkah 2: Buat proyek

Proyek merupakan kontainer resource tingkat teratas di SLS. Semua penyimpanan log, indeks, dan dasbor termasuk dalam sebuah proyek.

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));
    // Tunggu hingga proyek sepenuhnya tersedia setelah pembuatan
    TimeUnit.SECONDS.sleep(60 * 2);
}
Tunggu selama 2 menit untuk mengakomodasi waktu yang diperlukan agar proyek sepenuhnya tersedia setelah dibuat. Di lingkungan produksi, gunakan polling atau logika retry alih-alih sleep tetap.

Langkah 3: Buat penyimpanan log

Penyimpanan log adalah unit dalam proyek yang mengumpulkan, menyimpan, dan mengkueri data log. Setiap penyimpanan log memiliki periode retensi dan jumlah shard yang dapat dikonfigurasi.

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

static void createLogstore() throws LogException, InterruptedException {
    System.out.println("ready to create logstore");
    int ttlInDay = 3;     // Periode retensi data dalam hari. Atur ke 3650 untuk penyimpanan permanen.
    int shardCount = 2;   // Jumlah shard untuk throughput baca/tulis
    LogStore store = new LogStore(logstoreName, ttlInDay, shardCount);
    client.CreateLogStore(projectName, store);
    System.out.println(String.format("create logstore %s success", logstoreName));
    // Tunggu hingga penyimpanan log tersedia
    TimeUnit.SECONDS.sleep(60);
}
ParameterDeskripsiContoh
ttlInDayPeriode retensi data dalam hari. Atur ke 3650 untuk penyimpanan permanen.3
shardCountJumlah shard. Semakin banyak shard, semakin tinggi throughput baca/tulis.2

Langkah 4: Buat indeks

Indeks memungkinkan pencarian dan analitik log pada penyimpanan log. Contoh ini membuat indeks teks penuh dan indeks bidang untuk field dev dan id.

static void createIndex() throws LogException, InterruptedException {
    System.out.println(String.format("ready to create index for %s", logstoreName));
    // Konfigurasi indeks:
    // - Indeks teks penuh dengan pemisah kata standar (koma, spasi, tanda kutip, kurung siku, dll.)
    // - Indeks bidang pada "dev" (tipe teks) dan "id" (tipe long)
    // - Pencarian tidak peka huruf besar/kecil, tokenisasi bahasa Tiongkok dinonaktifkan, panjang teks maksimum 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));
    // Tunggu hingga indeks tersedia
    TimeUnit.SECONDS.sleep(60);
}

Konfigurasi JSON indeks mengatur pengaturan berikut:

PengaturanNilaiDeskripsi
Token indeks teks penuh, ' " ; = ( ) [ ] { } ? @ & < > / : \n \t \rPembatas untuk tokenisasi teks log
caseSensitivefalsePencarian tidak peka huruf besar/kecil
chnfalseTokenisasi bahasa Tiongkok dinonaktifkan
dev fieldtextBidang teks dengan analitik diaktifkan (doc_value: true)
id fieldlongBidang numerik dengan analitik diaktifkan (doc_value: true)
max_text_len2048Panjang teks maksimum untuk pengindeksan

Langkah 5: Tulis data log

Tulis 100 item log contoh ke penyimpanan log. Setiap item log berisi field id dan 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));
    // Tunggu sebentar agar log diindeks
    TimeUnit.SECONDS.sleep(5);
}
PutLogs cocok untuk skenario volume rendah. Untuk beban kerja ber-throughput tinggi atau konkurensi tinggi, gunakan Alibaba Cloud Log Java Producer, yang menyediakan batching, retry, dan pengiriman asinkron.

Langkah 6: Kueri log

Jalankan kueri SQL untuk mengambil log dari penyimpanan log dalam rentang waktu satu jam.

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

static void queryLogs() throws LogException {
    System.out.println(String.format("ready to query logs from %s", logstoreName));
    // Kueri satu jam terakhir. fromTime dan toTime adalah stempel waktu UNIX dalam detik.
    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("********************");
    }
}

Kode lengkap

Contoh berikut menggabungkan semua langkah sebelumnya menjadi satu program yang dapat dijalankan. Buat file bernama SlsQuickStart.java dan tempel kode di bawah ini.

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 {
    // Dapatkan kredensial dari variabel lingkungan
    static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    // Titik akhir SLS untuk China (Hangzhou). Ganti dengan titik akhir wilayah Anda.
    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();
    }
}

Output yang diharapkan

Setelah menjalankan SlsQuickStart.java, konsol akan mencetak:

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
********************
...
Output kueri aktual juga dapat mencakup field metadata sistem seperti __line__, __topic__, dan __time___0.

Referensi