All Products
Search
Document Center

Simple Log Service:Get started with Simple Log Service SDK for Java

Last Updated:Oct 26, 2023

This topic describes how to get started with Simple Log Service SDK for Java and perform common operations. For example, you can create a project, create a Logstore, write logs, and query logs.

Prerequisites

  • A Resource Access Management (RAM) user is created, and the required permissions are granted to the RAM user. For more information, see Create a RAM user and grant permissions to the RAM user.

  • The ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured. For more information, see Configure environment variables.

    Important
    • The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use the AccessKey pair of a RAM user to call API operations or perform routine O&M.

    • We recommend that you do not save the AccessKey ID or AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and the security of all resources within your account may be compromised.

  • Simple Log Service SDK for Java is installed. For more information, see Install Simple Log Service SDK for Java.

Sample code

In this example, a file named SLSQuickStart.java is created. The sample code in this file provides an example on how to call API operations to create a project, create a Logstore, create indexes, write logs, and query logs. Example:

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. 
    String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // The Simple Log Service endpoint. In this example, the Simple Log Service 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-project";
    // The name of the Logstore. 
    static String logstoreName = "aliyun-test-logstore";
    // The query statement. 
    static String query = "*| select * from " + logstoreName;

    // Create a 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));
        TimeUnit.SECONDS.sleep(60*2);
    }

    // Create a Logstore. 
     static void createLogstore() throws LogException, InterruptedException {
        System.out.println("ready to create logstore");
        int ttl_in_day = 3;     // The retention period of data. If you set this parameter to 3650, data is permanently stored. Unit: days. 
        int shard_count = 2;   // The number of shards. 
        LogStore store = new LogStore(logstoreName, ttl_in_day, shard_count);
        client.CreateLogStore(projectName, store);
        System.out.println(String.format("create logstore %s success",logstoreName));
        TimeUnit.SECONDS.sleep(60);
    }

    // Create indexes for the Logstore. 
     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 logs 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. 
     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. 
     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 query time range. 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 logs. 
        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

  • If the response that is returned by Log Service contains error information after you call an API operation, the call fails. You can handle errors based on the error codes that are returned when API calls fail. For more information, see Error codes.
  • Alibaba Cloud OpenAPI Explorer provides debugging capabilities, SDKs, examples, and related documents. You can use OpenAPI Explorer to debug Log Service API operations without the need to manually encapsulate or sign requests. For more information, visit OpenAPI Portal.
  • Log Service provides the command-line interface (CLI) to meet the requirements for automated configurations in Log Service. For more information, see Log Service CLI.
  • For more information about sample code, see Alibaba Cloud Log Service SDK for Java on GitHub.
  • For more information about sample code, see Alibaba Cloud Log Service SDK for Python on GitHub.