Use Simple Log Service (SLS) SDK for Java to create a project, logstore, and index, then write and query log data.
Prerequisites
Before you begin, make sure you have:
Java Runtime Environment (JRE) 6.0 or later installed. Run
java -versionto verify. If Java is not installed, download it from the Java official websiteSLS SDK for Java installed. For installation instructions, see Install SLS SDK for Java
-
An AccessKey ID and AccessKey secret created in the Alibaba Cloud console, stored as environment variables:
export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>
Step 1: Initialize the client
All steps in this tutorial share a single Client instance. The endpoint specifies which region handles your requests.
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);
}
Replace cn-hangzhou.log.aliyuncs.com with the endpoint for your region. The endpoint format is <region-id>.log.aliyuncs.com.
Step 2: Create a project
A project is the top-level resource container in SLS. Logstores, indexes, and dashboards all belong to a project.
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);
}
The 2-minute wait accounts for the time required for the project to become fully available. In production, use polling or retry logic instead of a fixed sleep.
Step 3: Create a logstore
A logstore collects, stores, and queries log data within a project. Configure its retention period and shard count to match your workload.
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);
}
|
Parameter |
Description |
Example |
|
|
Data retention period in days. Set to |
|
|
|
Number of shards. More shards increase read/write throughput. |
|
Step 4: Create an index
An index enables log search and analytics on a logstore. This example creates a full-text index and field indexes for the dev and id fields.
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);
}
The index JSON configures the following settings:
|
Setting |
Value |
Description |
|
Full-text index tokens |
|
Delimiters for tokenizing log text |
|
|
|
Case-insensitive search |
|
|
|
Chinese tokenization disabled |
|
|
|
Text field with analytics enabled ( |
|
|
|
Numeric field with analytics enabled ( |
|
|
|
Maximum text length for indexing |
Step 5: Write log data
Write 100 sample log events to the logstore. Each log event contains an id and a dev field.
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 is suitable for low-volume scenarios. For high-throughput or high-concurrency workloads, use Alibaba Cloud Log Java Producer , which provides batching, retry, and async sending.
Step 6: Query logs
Run an SQL query to retrieve log events from the logstore within a one-hour window.
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("********************");
}
}
Complete code
The following example combines all previous steps into a single runnable program. Create a file named SlsQuickStart.java and paste the code below.
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();
}
}
Expected output
After you run SlsQuickStart.java, the console prints:
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
********************
...
The actual query output may also include system metadata fields such as__line__,__topic__, and__time___0.