全部產品
Search
文件中心

Simple Log Service:Java SDK快速入門

更新時間:Jan 06, 2026

本文介紹如何快速使用Log ServiceJava SDK完成常見操作,包括建立專案(Project)、建立日誌庫(LogStore)、寫入日誌和查詢日誌等。

前提條件

您已完成以下操作:

  • 已安裝Java開發環境。

    Log ServiceJava SDK支援JRE 6.0及以上的Java運行環境,您可以執行java -version命令檢查您已安裝的Java版本。如果未安裝,可以從Java官方網站下載安裝包並完成安裝。

  • 已安裝Log ServiceJava SDK。具體操作,請參見安裝Java SDK

範例程式碼

本樣本中,建立一個SlsQuickStart.java檔案,並調用介面分別完成建立Project、建立LogStore、建立索引、寫入日誌資料和查詢日誌資料。樣本如下:

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 {
    /**
     * 本樣本從環境變數中擷取AccessKey ID和AccessKey Secret。
     */
    static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    /**
     * Log Service的服務存取點。此處以杭州為例,其它地區請根據實際情況填寫。
     */
    static String host = "cn-hangzhou.log.aliyuncs.com";
    /**
     * 建立Log ServiceClient。
     */
    static Client client = new Client(host, accessId, accessKey);
    /**
     * // Project名稱。
     */
    static String projectName = "aliyun-test-gs-project";
    /**
     * LogStore名稱。
     */
    static String logstoreName = "aliyun-test-logstore";
    /**
     * 查詢語句。
     */
    static String query = "*| select * from " + logstoreName;

    /**
     * 建立Project。
     *
     * @throws LogException
     * @throws InterruptedException
     */
    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);
    }

    /**
     * 建立LogStore。
     *
     * @throws LogException
     * @throws InterruptedException
     */
    static void createLogstore() throws LogException, InterruptedException {
        System.out.println("ready to create logstore");
        int ttlInDay = 3;     // 資料儲存時間。如果配置為3650,表示永久儲存。單位為天。
        int shardCount = 2;   // Shard數量。
        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);
    }

    /**
     * 為LogStore建立索引。
     *
     * @throws LogException
     * @throws InterruptedException
     */
    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);
    }

    /**
     * 向LogStore寫入資料。為了提高您系統的IO效率,請盡量不要直接使用該方式往Log Service中寫資料,此方式僅為功能舉例。在巨量資料、高並發情境下建議使用Aliyun Log Java Producer方式寫入日誌資料。
     *
     * @throws LogException
     * @throws InterruptedException
     */
    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);
    }

    /**
     * 通過SQL查詢日誌。
     *
     * @throws LogException
     */
    static void queryLogs() throws LogException {
        System.out.println(String.format("ready to query logs from %s", logstoreName));
        // fromTime和toTime表示查詢日誌的時間範圍,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 {
        /**
         *  建立Project。
         */
        createProject();
        /**
         * 建立LogStore。
         */
        createLogstore();
        /**
         * 建立索引。
         */
        createIndex();
        /**
         * 寫入日誌資料。
         */
        pushLogs();
        /**
         * 查詢日誌。
         */
        queryLogs();
    }
}

更多範例程式碼,請參見Aliyun Log Java SDK

返回結果

返回結果樣本如下:

ready to create project
create project aliyun-test-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
********************
dev : test_push
id : 3
********************
dev : test_push
id : 4
********************
........

相關文檔