Get started with Simple Log Service (SLS) SDK for Java to perform common operations such as creating projects, creating logstores, writing logs, and querying logs.
Prerequisites
Java development environment installed: SLS SDK for Java supports Java Runtime Environment (JRE) 6.0 and later. Check your Java version by running
java -version. If Java is not installed, download and install it from the Java official website.SLS SDK for Java installed: For installation instructions, see Install SLS SDK for Java.
AccessKey pair configured: Obtain your AccessKey ID and AccessKey secret from the Alibaba Cloud console. Store them as environment variables for secure access.
Sample code
This example creates a file named SlsQuickStart.java that demonstrates how to:
Create a project
Create a logstore
Create an index
Write log data
Query logs
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 {
/**
* In this example, the AccessKey ID and AccessKey secret are obtained from environment variables.
*/
static String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
static String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
/**
* The SLS endpoint. In this example, the SLS endpoint for the China (Hangzhou) region is used. Replace the parameter value with the actual endpoint.
*/
static String host = "cn-hangzhou.log.aliyuncs.com";
/**
* Create a Simple Log Service client.
*/
static Client client = new Client(host, accessId, accessKey);
/**
* // The name of the project.
*/
static String projectName = "aliyun-test-gs-project";
/**
* The name of the logstore.
*/
static String logstoreName = "aliyun-test-logstore";
/**
* The query statement.
*/
static String query = "*| select * from " + logstoreName;
/**
* Create a 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);
}
/**
* Create a logstore.
*
* @throws LogException
* @throws InterruptedException
*/
static void createLogstore() throws LogException, InterruptedException {
System.out.println("ready to create logstore");
int ttlInDay = 3; // The retention period of data. If you set this parameter to 3650, data is permanently stored. Unit: days.
int shardCount = 2; // The number of shards.
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);
}
/**
* Create indexes for the 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);
}
/**
* Write data to the logstore. To improve the I/O efficiency of your system, we recommend that you do not use this method to write data to Simple Log Service. This method is for reference only If you want to write data to Simple Log Service in big data and high concurrency scenarios, we recommend that you use Alibaba Cloud 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);
}
/**
* Execute an SQL statement to query logs.
*
* @throws LogException
*/
static void queryLogs() throws LogException {
System.out.println(String.format("ready to query logs from %s", logstoreName));
// The fromTime and toTime parameters specify the start time and end time of the time range within which you want to query logs. The values of the parameters are UNIX timestamps.
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 {
/**
* Create a project.
*/
createProject();
/**
* Create a logstore.
*/
createLogstore();
/**
* Create indexes.
*/
createIndex();
/**
* Write data.
*/
pushLogs();
/**
* Query logs.
*/
queryLogs();
}
}For more information about sample code, see Alibaba Cloud Simple Log Service SDK for Java.
Response
The following response is returned for the preceding example:
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
********************
........References
In addition to its native SDK, SLS also supports the common Alibaba Cloud SDKs. For more information, see Simple Log Service_SDK Center_Alibaba Cloud OpenAPI Explorer.