全部产品
Search
文档中心

日志服务:Java SDK快速入门

更新时间:Oct 26, 2023

本文介绍如何快速使用日志服务Java SDK完成常见操作,包括创建项目(Project)、创建日志库(Logstore)、写入日志和查询日志等。

前提条件

  • 已创建RAM用户并完成授权。具体操作,请参见创建RAM用户并完成授权

  • 已配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具体操作,请参见配置环境变量

    重要
    • 阿里云账号的AccessKey拥有所有API的访问权限,建议您使用RAM用户的AccessKey进行API访问或日常运维。

    • 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。

  • 已安装Java 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。
    String accessId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    String accessKey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // 日志服务的服务接入点。此处以杭州为例,其它地域请根据实际情况填写。 
    static String host = "cn-hangzhou.log.aliyuncs.com"; 
    // 创建日志服务Client。 
    static Client client = new Client(host, accessId, accessKey);
    // Project名称。
    static String projectName = "aliyun-test-project";
    // Logstore名称。
    static String logstoreName = "aliyun-test-logstore";
    // 查询语句。
    static String query = "*| select * from " + logstoreName;

    // 创建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);
    }

    // 创建Logstore。
     static void createLogstore() throws LogException, InterruptedException {
        System.out.println("ready to create logstore");
        int ttl_in_day = 3;     // 数据保存时间。如果配置为3650,表示永久保存。单位为天。
        int shard_count = 2;   // Shard数量。
        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);
    }

    // 为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);
    }

    // 向Logstore写入数据。
    // 为了提高您系统的IO效率,请尽量不要直接使用该方式往日志服务中写数据,此方式仅为功能举例。
    // 在大数据、高并发场景下建议使用Aliyun 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);
    }

    // 通过SQL查询日志。
     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
********************
........

相关文档

  • 在调用API接口过程中,若服务端返回结果中包含错误信息,则表示调用API接口失败。您可以参考API错误码对照表查找对应的解决方法。更多信息,请参见API错误处理对照表
  • 阿里云OpenAPI开发者门户提供调试、SDK、示例和配套文档。通过OpenAPI,您无需手动封装请求和签名操作,就可以快速对日志服务API进行调试。更多信息,请参见OpenAPI开发者门户
  • 为满足越来越多的自动化日志服务配置需求,日志服务提供命令行工具CLI(Command Line Interface)。更多信息,请参见日志服务命令行工具CLI
  • 更多示例代码,请参见Aliyun Log Java SDK on GitHub
  • 更多示例代码,请参见Aliyun Log Python SDK on GitHub