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

Prerequisites

  • Log Service SDK for Go is installed. For more information, see Install Log Service SDK for Go.
  • The proto dependency is installed. You can run the go get -u github.com/gogo/protobuf/proto command to install the proto dependency.

Sample code

In this example, the SLSQuickStart.go file is created. The sample code in this file shows how to call the required API operations to create a project, create a Logstore, create indexes, write log data, and query log data. Example:
package main

import (
    "fmt"
    sls "github.com/aliyun/aliyun-log-go-sdk"
    "github.com/gogo/protobuf/proto"
    "math/rand"
    "time"
)
func main() {
    // The endpoint of Log Service. For more information, see Endpoints. 
    // In this example, the endpoint of the China (Hangzhou) region is used. Replace the value of the parameter with the actual endpoint. 
    Endpoint := "cn-hangzhou.log.aliyuncs.com"
    // Configure the required information, such as an AccessKey pair, an endpoint, a project name, and a Logstore name. 
    // The AccessKey pair that is used to access Log Service. For more information, see AccessKey pair. An Alibaba Cloud account has permissions to call all API operations. Therefore, security risks may arise if you use the AccessKey pair of an Alibaba Cloud account. We recommend that you log on as a RAM user that has permissions to call API operations or perform routine O&M. 
    AccessKeyId := "your_access_key_id"
    AccessKeySecret := "your_access_key_secret"
    // The temporary Security Token Service (STS) token of the RAM user. If you leave the parameter empty, no STS token is used. For more information, see Assign a RAM role to an Alibaba Cloud account. 
    SecurityToken := ""
    // Create a Log Service client. 
    client := sls.CreateNormalInterface(Endpoint, AccessKeyId, AccessKeySecret, SecurityToken)

    // Create a project. 
    ProjectName := "aliyun-test-project"
    Description := "test"
    project, err := client.CreateProject(ProjectName, Description)
    if err != nil {
        fmt.Errorf("Create project : %s failed %v\n", ProjectName, err)
    }
    fmt.Printf("Project : %s created successfully.\n", project.Name)
    time.Sleep(120 * time.Second)

    // Create a Logstore. 
    LogStoreName := "aliyun-test-logstore"
    err = client.CreateLogStore(ProjectName, LogStoreName, 3, 2, true, 6)
    if err != nil {
        fmt.Errorf("Create LogStore : %s failed %v\n", LogStoreName, err)
    }
    fmt.Printf("Create logstore : %v successfully.\n", LogStoreName)
    time.Sleep(10 * time.Second)

    // Create indexes for the Logstore. 
    index := sls.Index{
        // Field indexes. 
        Keys: map[string]sls.IndexKey{
            "col_0": {
                Token:         []string{" "},
                CaseSensitive: false,
                Type:          "long",
            },
            "col_1": {
                Token:         []string{",", ":", " "},
                CaseSensitive: false,
                Type:          "text",
            },
        },
        // Full-text indexes. 
        Line: &sls.IndexLine{
            Token:         []string{",", ":", " "},
            CaseSensitive: false,
            IncludeKeys:   []string{},
            ExcludeKeys:   []string{},
        },
    }
    err = client.CreateIndex(ProjectName, LogStoreName, index)
    if err != nil {
        fmt.Errorf("Create Index failed %v\n", err)
    }
    fmt.Println("CreateIndex success")
    time.Sleep(60 * time.Second)

    // Write data to the Logstore. 
    for loggroupIdx := 0; loggroupIdx < 10; loggroupIdx++ {
        logs := []*sls.Log{}
        for logIdx := 0; logIdx < 100; logIdx++ {
            content := []*sls.LogContent{}
            for colIdx := 0; colIdx < 10; colIdx++ {
                if colIdx == 0 {
                    content = append(content, &sls.LogContent{
                        Key:   proto.String(fmt.Sprintf("col_%d", colIdx)),
                        Value: proto.String(fmt.Sprintf("%d", rand.Intn(10000000))),
                    })
                } else {
                    content = append(content, &sls.LogContent{
                        Key:   proto.String(fmt.Sprintf("col_%d", colIdx)),
                        Value: proto.String(fmt.Sprintf("loggroup idx: %d, log idx: %d, col idx: %d, value: %d", loggroupIdx, logIdx, colIdx, rand.Intn(10000000))),
                    })
                }
            }
            log := &sls.Log{
                Time:     proto.Uint32(uint32(time.Now().Unix())),
                Contents: content,
            }
            logs = append(logs, log)
        }
        loggroup := &sls.LogGroup{
            Topic:  proto.String("test"),
            Source: proto.String("10.238.222.116"),
            Logs:   logs,
        }
        
        err = client.PutLogs(ProjectName, LogStoreName, loggroup)
        if err == nil {
            fmt.Println("PutLogs success")
        } else {
            fmt.Errorf("PutLogs failed %v\n", err)
        }
        time.Sleep(time.Second)
    }

    // Execute an SQL statement to query log data. 
    response, err := client.GetLogs(ProjectName, LogStoreName, "test", time.Now().Unix()-1800, time.Now().Unix(), "* and col_0 > 9000000", 100, 1, true)
    if err != nil {
        fmt.Errorf("GetLogs failed %v\n", err)
    }
    fmt.Printf("Get %d logs\n", response.Count)
    logs := response.Logs
    for i := range logs {
        for k, v := range logs[i] {
            fmt.Printf("key: %s, value: %s\n", k, v)
        }
        fmt.Println("======")
    }
}

For more information about sample code, see Alibaba Cloud Log Service SDK for Go.

Response

In this example, the following result is returned:

Project : aliyun-test-project created successfully.
Create logstore : aliyun-test-logstore successfully.
CreateIndex success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
PutLogs success
Get 61 logs
key: source, value: 10.238.222.116
key: time, value: 1627282116
key: col_0, value: 9886757
key: col_1, value: loggroup idx: 6, log idx: 87, col idx: 1, value: 2673724
key: col_2, value: loggroup idx: 6, log idx: 87, col idx: 2, value: 5822012
key: col_8, value: loggroup idx: 6, log idx: 87, col idx: 8, value: 3996746
key: topic, value: test
key: col_9, value: loggroup idx: 6, log idx: 87, col idx: 9, value: 7646111
key: col_3, value: loggroup idx: 6, log idx: 87, col idx: 3, value: 8872632
key: col_4, value: loggroup idx: 6, log idx: 87, col idx: 4, value: 1839836
key: col_5, value: loggroup idx: 6, log idx: 87, col idx: 5, value: 6967415
key: col_6, value: loggroup idx: 6, log idx: 87, col idx: 6, value: 5872057
key: col_7, value: loggroup idx: 6, log idx: 87, col idx: 7, value: 3227909
======
......