All Products
Search
Document Center

Simple Log Service:Use Simple Log Service SDK for Go to manage alerts

Last Updated:Apr 17, 2024

This topic provides the sample code of Simple Log Service SDK for Go to show how to use the alerting feature.

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 Go V0.1.37 or later is installed. For more information, see Install Simple Log Service SDK for Go.

Manage alert monitoring rules

The following sample code is provided for your reference. For more information about the parameters in the sample code, see Data structure of an alert monitoring rule.

package main

import (
    "fmt"
    "os"
    sls "github.com/aliyun/aliyun-log-go-sdk"
)

var (
    // The Simple Log Service endpoint. 
    endpoint        = "cn-huhehaote.log.aliyuncs.com"
    // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    accessKeyId     = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    accessKeySecret = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") 
    // Create a Simple Log Service client. 
    client          = sls.CreateNormalInterface(endpoint, accessKeyId, accessKeySecret, "")
    project         = "demo-alert"
    alertId         = "nginx-status-error"
)

func createAlert() {
    alert := &sls.Alert{
        Name:        alertId,
        DisplayName: "Nginx Status Error",
        State:       "Enabled",
        Schedule: &sls.Schedule{
            Type:     sls.ScheduleTypeFixedRate,
            Interval: "1m",
        },
        Configuration: &sls.AlertConfiguration{
            Version:   "2.0",
            Type:      "default",
            Dashboard: "internal-alert-analysis",
            QueryList: []*sls.AlertQuery{
                &sls.AlertQuery{
                    StoreType:    "log",
                    Region:       "cn-huhehaote",
                    Project:      project,
                    Store:        "nginx-access-log",
                    Query:        "status >= 400 | select count(*) as cnt",
                    TimeSpanType: "Truncated",
                    Start:        "-1m",
                    End:          "absolute",
                    PowerSqlMode: sls.PowerSqlModeAuto,
                },
            },
            GroupConfiguration: sls.GroupConfiguration{
                Type: sls.GroupTypeNoGroup,
            },
            JoinConfigurations: []*sls.JoinConfiguration{},
            SeverityConfigurations: []*sls.SeverityConfiguration{
                &sls.SeverityConfiguration{
                    Severity: sls.Medium,
                    EvalCondition: sls.ConditionConfiguration{
                        Condition:      "cnt > 0",
                        CountCondition: "",
                    },
                },
            },
            Labels: []*sls.Tag{
                &sls.Tag{
                    Key:   "service",
                    Value: "nginx",
                },
            },
            Annotations: []*sls.Tag{
                &sls.Tag{
                    Key:   "title",
                    Value: "Nginx Status Error",
                },
                &sls.Tag{
                    Key:   "desc",
                    Value: "Nginx Status Error, count: ${cnt}",
                },
            },
            AutoAnnotation: true,
            SendResolved:   false,
            Threshold:      1,
            NoDataFire:     false,
            NoDataSeverity: sls.Medium,
            PolicyConfiguration: sls.PolicyConfiguration{
                AlertPolicyId:  "sls.builtin.dynamic",
                ActionPolicyId: "test-action-policy",
                RepeatInterval: "1m",
                UseDefault:     false,
            },
        },
    }
    err := client.CreateAlert(project, alert)
    fmt.Println("[create alert]", err)
}

func getAndUpdateAlert() {
    alert, err := client.GetAlert(project, alertId)
    fmt.Println("[get alert]", sls.JsonMarshal(alert), err)

    alert.Configuration.QueryList[0].Query = "status >= 500 | select count(*) as cnt"
    err = client.UpdateAlert(project, alert)
    fmt.Println("[update alert]", err)
}

func disableAndEnableAlert() {
    err := client.DisableAlert(project, alertId)
    fmt.Println("[disable alert]", err)

    err = client.EnableAlert(project, alertId)
    fmt.Println("[enable alert]", err)
}

func listAlerts() {
    alerts, total, count, err := client.ListAlert(project, "", "", 0, 100)
    fmt.Println("[list alert]", sls.JsonMarshal(alerts), total, count, err)
}

func deleteAlert() {
    err := client.DeleteAlert(project, alertId)
    fmt.Println("[delete alert]", err)
}

func main() {
    createAlert()
    getAndUpdateAlert()
    disableAndEnableAlert()
    listAlerts()
    deleteAlert()
}

Manage alert resource data

The following sample code is provided for your reference. For more information about the parameters in the sample code, see Data structure of alert resource data.

Manage users

package main

import (
    "fmt"
    "os"
    sls "github.com/aliyun/aliyun-log-go-sdk"
)

var (
    // The Simple Log Service endpoint. For the resource data, the write operations support only the Simple Log Service endpoint for the China (Heyuan) region, and the read operations support the Simple Log Service endpoints for other regions. 
    endpoint        = "cn-heyuan.log.aliyuncs.com"
    // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    accessKeyId     = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
    accessKeySecret = os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") 
    // Create a Simple Log Service client. 
    client           = sls.CreateNormalInterface(endpoint, accessKeyId, accessKeySecret, "")
    userResourceName = "sls.common.user"
)

func createUser() {
    user := &sls.ResourceUser{
        UserId:       "alex",
        UserName:     "Alex",
        Enabled:      true,
        CountryCode:  "86",
        Phone:        "133****3333",
        Email:        []string{"****@example.com"},
        SmsEnabled:   true,
        VoiceEnabled: true,
    }
    record := &sls.ResourceRecord{
        Id:    user.UserId,
        Tag:   user.UserName,
        Value: sls.JsonMarshal(user),
    }
    err := client.CreateResourceRecord(userResourceName, record)
    fmt.Println("[create user]", err)
}

func getUser() {
    record, err := client.GetResourceRecord(userResourceName, "alex")
    fmt.Println("[list user]", sls.JsonMarshal(record), err)
}

func updateUser() {
    user := &sls.ResourceUser{
        UserId:       "alex",
        UserName:     "Alex",
        Enabled:      false,
        CountryCode:  "86",
        Phone:        "133****3333",
        Email:        []string{"****@example.com"},
        SmsEnabled:   true,
        VoiceEnabled: true,
    }
    record := &sls.ResourceRecord{
        Id:    user.UserId,
        Tag:   user.UserName,
        Value: sls.JsonMarshal(user),
    }
    err := client.UpdateResourceRecord(userResourceName, record)
    fmt.Println("[update user]", err)
}

func listUsers() {
    records, count, total, err := client.ListResourceRecord(userResourceName, 0, 100)
    fmt.Println("[list users]", sls.JsonMarshal(records), count, total, err)
}

func deleteUser() {
    err := client.DeleteResourceRecord(userResourceName, "alex")
    fmt.Println("[delete user]", err)
}

func main() {
    createUser()
    getUser()
    updateUser()
    listUsers()
    deleteUser()
}

Manage user groups

userGroup := &sls.ResourceUserGroup{
    Id:      "devops",
    Name:    "DevOps Team",
    Enabled: true,
    Members: []string{"alex"},
}
record := &sls.ResourceRecord{
    Id:    userGroup.Id,
    Tag:   userGroup.Name,
    Value: sls.JsonMarshal(userGroup),
}
err := client.CreateResourceRecord("sls.common.user_group", record)
fmt.Println("[create user group]", err)

Manage webhook integration

webhooks := []*sls.WebhookIntegration{
    &sls.WebhookIntegration{
        Id:      "dingtalk",
        Name:    "Dingtalk Webhook",
        Method:  "POST",
        Url:     "https://oapi.dingtalk.com/robot/send?access_token=**********",
        Type:    "dingtalk",
        // The value of Additional Signature for your DingTalk chatbot. If you select Additional Signature for Security Settings when you create the DingTalk chatbot, you must configure this field. You can obtain the value of Additional Signature on the chatbot management page of DingTalk. 
        // Secret:  "SEC**********",
        Headers: []*sls.ResourceWebhookHeader{},
    },
    &sls.WebhookIntegration{
        Id:      "wechat",
        Name:    "Wechat Webhook",
        Method:  "POST",
        Url:     "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=**********",
        Type:    "wechat",
        Headers: []*sls.ResourceWebhookHeader{},
    },
    &sls.WebhookIntegration{
        Id:      "feishu",
        Name:    "Feishu Webhook",
        Method:  "POST",
        Url:     "https://open.feishu.cn/open-apis/bot/v2/hook/**********",
        Type:    "lark",
        // The value of Set signature verification for your Lark bot. If you select Set signature verification for Security settings when you create the Lark bot, you must configure this field. You can obtain the value of Set signature verification on the bot management page of Lark. 
        // Secret:  "**********",
        Headers: []*sls.ResourceWebhookHeader{},
    },
    &sls.WebhookIntegration{
        Id:      "slack",
        Name:    "Slack Webhook",
        Method:  "POST",
        Url:     "https://hooks.slack.com/services/**********",
        Type:    "slack",
        Headers: []*sls.ResourceWebhookHeader{},
    },
    &sls.WebhookIntegration{
        Id:     "webhook",
        Name:   "Common Webhook",
        Method: "POST",
        Url:    "https://example.com/***********",
        Type:   "custom",
        Headers: []*sls.ResourceWebhookHeader{
            &sls.ResourceWebhookHeader{
                Key:   "Authorization",
                Value: "Basic YWRtaW46Zm9vYmFy",
            },
        },
    },
}

for _, webhook := range webhooks {
    record := &sls.ResourceRecord{
        Id:    webhook.Id,
        Tag:   webhook.Name,
        Value: sls.JsonMarshal(webhook),
    }
    err := client.CreateResourceRecord("sls.alert.action_webhook", record)
    fmt.Println("[create webhook integration]", record.Id, err)
}

Manage action policies

actionPolicy := &sls.ResourceActionPolicy{
    ActionPolicyId:              "test-action-policy",
    ActionPolicyName:            "Test Action Policy",
    PrimaryPolicyScript:         `fire(type="sms", users=["alex"], groups=[], oncall_groups=[], receiver_type="static", external_url="", external_headers={}, template_id="sls.builtin.cn", period="any")`,
    SecondaryPolicyScript:       `fire(type="voice", users=["alex"], groups=[], oncall_groups=[], receiver_type="static", external_url="", external_headers={}, template_id="sls.builtin.cn", period="any")`,
    EscalationStartEnabled:      false,
    EscalationStartTimeout:      "10m",
    EscalationInprogressEnabled: false,
    EscalationInprogressTimeout: "30m",
    EscalationEnabled:           true,
    EscalationTimeout:           "1h",
}
record := &sls.ResourceRecord{
    Id:    actionPolicy.ActionPolicyId,
    Tag:   actionPolicy.ActionPolicyName,
    Value: sls.JsonMarshal(actionPolicy),
}
err := client.CreateResourceRecord("sls.alert.action_policy", record)
fmt.Println("[create action policy]", err)

Manage alert policies

alertPolicy := &sls.ResourceAlertPolicy{
    PolicyId:      "test-alert-policy",
    PolicyName:    "Test Alert Policy",
    Parent:        "",
    GroupPolicy:   `fire(action_policy="test-action-policy", group={"alert.alert_id": alert.alert_id}, group_by_all_labels=true, group_wait="15s", group_interval="5m", repeat_interval="1h")`,
    InhibitPolicy: "",
    SilencePolicy: "",
}
record := &sls.ResourceRecord{
    Id:    alertPolicy.PolicyId,
    Tag:   alertPolicy.PolicyName,
    Value: sls.JsonMarshal(alertPolicy),
}
err := client.CreateResourceRecord("sls.alert.alert_policy", record)
fmt.Println("[create alert policy]", err)

Manage alert templates

template := &sls.ResourceContentTemplate{
    TemplateId:   "test-template",
    TemplateName: "Test Template",
    Templates: sls.ResourceTemplates{
        Sms: sls.ResourceTemplate{
            Locale:  "zh-CN",
            Content: "",
        },
        Voice: sls.ResourceTemplate{
            Locale:  "zh-CN",
            Content: "",
        },
        Email: sls.ResourceTemplate{
            Locale:  "en-US",
            Subject: "SLS Alert",
            Content: "",
        },
        Dingtalk: sls.ResourceTemplate{
            Locale:  "zh-CN",
            Title:   "SLS Alert",
            Content: "",
        },
        Wechat: sls.ResourceTemplate{
            Locale:  "zh-CN",
            Title:   "SLS Alert",
            Content: "",
        },
        Lark: sls.ResourceTemplate{
            Locale:  "zh-CN",
            Title:   "SLS Alert",
            Content: "",
        },
        Slack: sls.ResourceTemplate{
            Locale:  "zh-CN",
            Title:   "SLS Alert",
            Content: "",
        },
        Webhook: sls.ResourceTemplate{
            Locale:   "zh-CN",
            SendType: "single",
            Limit:    0,
            Content:  "",
        },
    },
}
record := &sls.ResourceRecord{
    Id:    template.TemplateId,
    Tag:   template.TemplateName,
    Value: sls.JsonMarshal(template),
}
err := client.CreateResourceRecord("sls.alert.content_template", record)
fmt.Println("[create content template]", err)