全部产品
Search
文档中心

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

更新时间:Jul 02, 2025

Topik ini menjelaskan cara memulai menggunakan Simple Log Service SDK untuk Java dan melakukan operasi umum, seperti membuat Proyek, membuat penyimpanan log, menulis log, serta menanyakan log.

Prasyarat

  • Simple Log Service telah diaktifkan. Untuk informasi lebih lanjut, lihat Aktivasi Simple Log Service.

  • Pengguna Resource Access Management (RAM) telah dibuat, dan izin yang diperlukan telah diberikan kepada pengguna RAM. Untuk informasi lebih lanjut, lihat Buat pengguna RAM dan berikan izin kepada pengguna RAM.

  • Variabel lingkungan ALIBABA_CLOUD_ACCESS_KEY_ID dan ALIBABA_CLOUD_ACCESS_KEY_SECRET telah dikonfigurasi. Untuk informasi lebih lanjut, lihat Konfigurasikan variabel lingkungan di Linux, macOS, dan Windows.

    Penting
    • Pasangan AccessKey akun Alibaba Cloud memiliki izin untuk semua Operasi API. Kami sarankan Anda menggunakan pasangan AccessKey dari pengguna RAM untuk memanggil Operasi API atau melakukan pemeliharaan rutin O&M.

    • Kami sarankan Anda tidak menyimpan ID AccessKey atau Rahasia AccessKey dalam kode proyek Anda. Jika tidak, pasangan AccessKey mungkin bocor, dan keamanan semua sumber daya dalam akun Anda dapat terganggu.

  • Lingkungan pengembangan Java telah diinstal.

    Simple Log Service SDK untuk Java mendukung Java Runtime Environment (JRE) 6.0 dan versi yang lebih baru. Anda dapat menjalankan perintah java -version untuk memeriksa versi JRE Anda. Jika JRE belum diinstal, Anda dapat mengunduh paket instalasi dari situs resmi Java dan menginstal JRE.

  • Simple Log Service SDK untuk Java telah diinstal. Untuk informasi lebih lanjut, lihat Instal Simple Log Service SDK untuk Java.

Kode contoh

Dalam contoh ini, file bernama SlsQuickStart.java dibuat. Kode contoh dalam file ini memberikan contoh tentang cara memanggil Operasi API untuk membuat Proyek, membuat penyimpanan log, membuat indeks, menulis log, dan menanyakan log. Contoh:

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 {
    /**
     * Dalam contoh ini, ID AccessKey dan Rahasia AccessKey diperoleh 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 Simple Log Service. Dalam contoh ini, titik akhir Simple Log Service untuk wilayah China (Hangzhou) digunakan. Ganti nilai parameter dengan titik akhir sebenarnya.
     */
    static String host = "cn-hangzhou.log.aliyuncs.com";
    /**
     * Buat klien Simple Log Service.
     */
    static Client client = new Client(host, accessId, accessKey);
    /**
     * // Nama Proyek.
     */
    static String projectName = "aliyun-test-gs-project";
    /**
     * Nama penyimpanan log.
     */
    static String logstoreName = "aliyun-test-logstore";
    /**
     * Pernyataan query.
     */
    static String query = "*| select * from " + logstoreName;

    /**
     * Buat Proyek.
     *
     * @throws LogException
     * @throws InterruptedException
     */
    static void createProject() throws LogException, InterruptedException {
        String projectDescription = "deskripsi proyek";
        System.out.println("siap membuat proyek");
        client.CreateProject(projectName, projectDescription);
        System.out.println(String.format("buat proyek %s berhasil", projectName));
        TimeUnit.SECONDS.sleep(60 * 2);
    }

    /**
     * Buat penyimpanan log.
     *
     * @throws LogException
     * @throws InterruptedException
     */
    static void createLogstore() throws LogException, InterruptedException {
        System.out.println("siap membuat penyimpanan log");
        int ttlInDay = 3;     // Periode retensi data. Jika Anda menyetel parameter ini ke 3650, data disimpan secara permanen. Unit: hari.
        int shardCount = 2;   // Jumlah shard.
        LogStore store = new LogStore(logstoreName, ttlInDay, shardCount);
        client.CreateLogStore(projectName, store);
        System.out.println(String.format("buat penyimpanan log %s berhasil", logstoreName));
        TimeUnit.SECONDS.sleep(60);
    }

    /**
     * Buat indeks untuk penyimpanan log.
     *
     * @throws LogException
     * @throws InterruptedException
     */
    static void createIndex() throws LogException, InterruptedException {
        System.out.println(String.format("siap membuat indeks untuk %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("buat indeks untuk %s berhasil", logstoreName));
        TimeUnit.SECONDS.sleep(60);
    }

    /**
     * Tulis data ke penyimpanan log. Untuk meningkatkan efisiensi I/O sistem Anda, kami sarankan Anda tidak menggunakan metode ini untuk menulis data ke Simple Log Service. Metode ini hanya untuk referensi. Jika Anda ingin menulis data ke Simple Log Service dalam skenario data besar dan konkurensi tinggi, kami sarankan Anda menggunakan Alibaba Cloud Log Java Producer.
     *
     * @throws LogException
     * @throws InterruptedException
     */
    static void pushLogs() throws LogException, InterruptedException {
        System.out.println(String.format("siap mendorong log untuk %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("mendorong log untuk %s berhasil", logstoreName));
        TimeUnit.SECONDS.sleep(5);
    }

    /**
     * Jalankan pernyataan SQL untuk menanyakan log.
     *
     * @throws LogException
     */
    static void queryLogs() throws LogException {
        System.out.println(String.format("siap menanyakan log dari %s", logstoreName));
        // Parameter fromTime dan toTime menentukan waktu mulai dan waktu akhir rentang waktu tempat Anda ingin menanyakan log. Nilai parameter adalah timestamp UNIX.
        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 {
        /**
         * Buat Proyek.
         */
        createProject();
        /**
         * Buat penyimpanan log.
         */
        createLogstore();
        /**
         * Buat indeks.
         */
        createIndex();
        /**
         * Tulis data.
         */
        pushLogs();
        /**
         * Tanyakan log.
         */
        queryLogs();
    }
}

Untuk informasi lebih lanjut tentang kode contoh, lihat Alibaba Cloud Simple Log Service SDK untuk Java.

Respon

Berikut adalah respon yang dikembalikan untuk contoh sebelumnya:

siap membuat proyek
buat proyek aliyun-test-project berhasil
siap membuat penyimpanan log
buat penyimpanan log aliyun-test-logstore berhasil
siap membuat indeks untuk aliyun-test-logstore
buat indeks untuk aliyun-test-logstore berhasil
siap mendorong log untuk aliyun-test-logstore
mendorong log untuk aliyun-test-logstore berhasil
siap menanyakan log dari aliyun-test-logstore
dev : test_push
id : 0
********************
dev : test_push
id : 1
********************
dev : test_push
id : 2
********************
dev : test_push
id : 3
********************
dev : test_push
id : 4
********************
........

Referensi