All Products
Search
Document Center

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

Last Updated:Oct 26, 2023

This topic provides the sample code of Simple Log Service SDK for Java 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 Java V0.6.71 or later is installed. For more information, see Install Simple Log Service SDK for Java.

Manage alert monitoring rules

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

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.*;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.*;
import com.aliyun.openservices.log.response.*;

import java.util.*;

public class App {
    // The Simple Log Service endpoint. 
    private static final String ENDPOINT = "cn-huhehaote.log.aliyuncs.com";
    // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    // Create a Simple Log Service client. 
    private static final Client client = new Client(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    private static final String PROJECT = "demo-alert";
    private static final String ALERT_ID = "nginx-status-error";

    private static void createAlert() throws LogException {
        JobSchedule schedule = new JobSchedule();
        schedule.setType(JobScheduleType.FIXED_RATE);
        schedule.setInterval("1m");

        AlertConfiguration configuration = new AlertConfiguration();
        configuration.setVersion("2.0");
        configuration.setType("default");
        configuration.setDashboard("internal-alert-analysis");

        Query query = new Query();
        query.setStoreType("log");
        query.setRegion("cn-huhehaote");
        query.setProject(PROJECT);
        query.setStore("nginx-access-log");
        query.setQuery("status >= 400 | select count(*) as cnt");
        query.setTimeSpanType(TimeSpanType.TRUNCATED);
        query.setStart("-1m");
        query.setEnd("absolute");
        query.setPowerSqlMode("auto");
        configuration.setQueryList(Collections.singletonList(query));

        AlertConfiguration.GroupConfiguration groupConfiguration = new AlertConfiguration.GroupConfiguration();
        groupConfiguration.setType("no_group");
        configuration.setGroupConfiguration(groupConfiguration);

        AlertConfiguration.SeverityConfiguration severityConfiguration = new AlertConfiguration.SeverityConfiguration();
        severityConfiguration.setSeverity(AlertConfiguration.Severity.Medium);
        AlertConfiguration.ConditionConfiguration conditionConfiguration = new AlertConfiguration.ConditionConfiguration();
        conditionConfiguration.setCondition("cnt > 0");
        conditionConfiguration.setCountCondition("");
        severityConfiguration.setEvalCondition(conditionConfiguration);
        configuration.setSeverityConfigurations(Collections.singletonList(severityConfiguration));

        AlertConfiguration.Tag serviceLabel = new AlertConfiguration.Tag();
        serviceLabel.setKey("service");
        serviceLabel.setValue("nginx");
        configuration.setLabels(Collections.singletonList(serviceLabel));

        AlertConfiguration.Tag titleAnno = new AlertConfiguration.Tag();
        titleAnno.setKey("title");
        titleAnno.setValue("Nginx Status Error");
        AlertConfiguration.Tag descAnno = new AlertConfiguration.Tag();
        descAnno.setKey("desc");
        descAnno.setValue("Nginx Status Error, count: ${cnt}");
        List<AlertConfiguration.Tag> annotations = new LinkedList<AlertConfiguration.Tag>();
        annotations.add(titleAnno);
        annotations.add(descAnno);
        configuration.setAnnotations(annotations);

        configuration.setAutoAnnotation(true);
        configuration.setSendResolved(false);
        configuration.setThreshold(1);
        configuration.setNoDataFire(false);
        configuration.setNoDataSeverity(AlertConfiguration.Severity.Medium);

        AlertConfiguration.PolicyConfiguration policyConfiguration = new AlertConfiguration.PolicyConfiguration();
        policyConfiguration.setAlertPolicyId("sls.builtin.dynamic");
        policyConfiguration.setActionPolicyId("test-action-policy");
        policyConfiguration.setRepeatInterval("1m");
        policyConfiguration.setUseDefault(false);
        configuration.setPolicyConfiguration(policyConfiguration);

        Alert alert = new Alert();
        alert.setName(ALERT_ID);
        alert.setDisplayName("Nginx Status Error");
        alert.setState(JobState.ENABLED);
        alert.setSchedule(schedule);
        alert.setConfiguration(configuration);

        CreateAlertRequest request = new CreateAlertRequest(PROJECT, alert);
        CreateAlertResponse response = client.createAlert(request);
        System.out.println("[create alert] " + JSON.toJSONString(response));
    }

    public static void getAndUpdateAlert() throws LogException {
        GetAlertRequest getAlertRequest = new GetAlertRequest(PROJECT, ALERT_ID);
        GetAlertResponse getAlertResponse = client.getAlert(getAlertRequest);
        System.out.println("[get alert] " + JSON.toJSONString(getAlertResponse));

        Alert alert = getAlertResponse.getAlert();
        alert.getConfiguration().getQueryList().get(0).setQuery("status >= 500 | select count(*) as cnt");

        UpdateAlertRequest updateAlertRequest = new UpdateAlertRequest(PROJECT, alert);
        UpdateAlertResponse updateAlertResponse = client.updateAlert(updateAlertRequest);
        System.out.println("[update alert] " + JSON.toJSONString(updateAlertResponse));
    }

    public static void disableAndEnableAlert() throws LogException {
        DisableAlertRequest disableAlertRequest = new DisableAlertRequest(PROJECT, ALERT_ID);
        DisableAlertResponse disableAlertResponse = client.disableAlert(disableAlertRequest);
        System.out.println("[disable alert] " + JSON.toJSONString(disableAlertResponse));

        EnableAlertRequest enableAlertRequest = new EnableAlertRequest(PROJECT, ALERT_ID);
        EnableAlertResponse enableAlertResponse = client.enableAlert(enableAlertRequest);
        System.out.println("[enable alert] " + JSON.toJSONString(enableAlertResponse));
    }

    public static void listAlerts() throws LogException {
        ListAlertRequest request = new ListAlertRequest(PROJECT);
        request.setOffset(0);
        request.setSize(100);
        ListAlertResponse response = client.listAlert(request);
        System.out.println("[list alerts] " + JSON.toJSONString(response));
    }

    public static void deleteAlert() throws LogException {
        DeleteAlertRequest request = new DeleteAlertRequest(PROJECT, ALERT_ID);
        DeleteAlertResponse response = client.deleteAlert(request);
        System.out.println("[delete alert] " + JSON.toJSONString(response));
    }

    public static void main(String[] args) throws LogException {
        createAlert();
        getAndUpdateAlert();
        disableAndEnableAlert();
        listAlerts();
        deleteAlert();
    }
}
            

Manage alert resource data

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

Manage users

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.*;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.*;
import com.aliyun.openservices.log.response.*;

import java.util.Collections;

public class App {
    
    // 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. 
    private static final String ENDPOINT = "cn-heyuan.log.aliyuncs.com";
    // In this example, the AccessKey ID and AccessKey secret are obtained from environment variables. 
    private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    private static final String USER_RESOURCE_NAME = "sls.common.user";
    private static Client client = new Client(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

    private static void createUser() throws LogException {
        ResourceUser user = new ResourceUser();
        user.setUserId("alex");
        user.setUserName("Alex");
        user.setEnabled(true);
        user.setCountryCode("86");
        user.setPhone("133****3333");
        user.setEmail(Collections.singletonList("****@example.com"));
        user.setSmsEnabled(true);
        user.setVoiceEnabled(true);

        ResourceRecord record = new ResourceRecord();
        record.setId(user.getUserId());
        record.setTag(user.getUserName());
        record.setValue(JSON.toJSONString(user));

        CreateResourceRecordRequest request = new CreateResourceRecordRequest(USER_RESOURCE_NAME, record);
        CreateResourceRecordResponse response = client.createResourceRecord(request);
        System.out.println("[create user]" + JSON.toJSONString(response));
    }

    private static void getUser() throws LogException {
        GetResourceRecordRequest request = new GetResourceRecordRequest(USER_RESOURCE_NAME, "alex");
        GetResourceRecordResponse response = client.getResourceRecord(request);
        System.out.println("[get user]" + JSON.toJSONString(response.getRecord()));
    }

    private static void updateUser() throws LogException {
        ResourceUser user = new ResourceUser();
        user.setUserId("alex");
        user.setUserName("Alex");
        user.setEnabled(false);
        user.setCountryCode("86");
        user.setPhone("133****3333");
        user.setEmail(Collections.singletonList("****@example.com"));
        user.setSmsEnabled(true);
        user.setVoiceEnabled(true);

        ResourceRecord record = new ResourceRecord();
        record.setId(user.getUserId());
        record.setTag(user.getUserName());
        record.setValue(JSON.toJSONString(user));

        UpdateResourceRecordRequest request = new UpdateResourceRecordRequest(USER_RESOURCE_NAME, record);
        UpdateResourceRecordResponse response = client.updateResourceRecord(request);
        System.out.println("[update user]" + JSON.toJSONString(response));
    }

    private static void listUsers() throws LogException {
        ListResourceRecordRequest request = new ListResourceRecordRequest(USER_RESOURCE_NAME);
        request.setOffset(0);
        request.setSize(100);

        ListResourceRecordResponse response = client.listResourceRecord(request);
        System.out.printf("[list users] count: %d, total %d, data %s",
                response.getCount(), response.getTotal(), JSON.toJSONString(response.getRecords()));
    }

    private static void deleteUser() throws LogException {
        DeleteResourceRecordRequest request = new DeleteResourceRecordRequest(USER_RESOURCE_NAME, "alex");
        DeleteResourceRecordResponse response = client.deleteResourceRecord(request);
        System.out.println("[delete user]" + JSON.toJSONString(response));
    }

    public static void main(String[] args) throws LogException {
        createUser();
        getUser();
        updateUser();
        listUsers();
        deleteUser();
    }
}
            

Manage user groups

private static void createUserGroup() throws LogException {
    ResourceUserGroup userGroup = new ResourceUserGroup();
    userGroup.setGroupId("devops");
    userGroup.setGroupName("DevOps Team");
    userGroup.setEnabled(true);
    userGroup.setMembers(Collections.singletonList("alex"));

    ResourceRecord record = new ResourceRecord();
    record.setId(userGroup.getGroupId());
    record.setTag(userGroup.getGroupName());
    record.setValue(JSON.toJSONString(userGroup));

    CreateResourceRecordRequest request = new CreateResourceRecordRequest("sls.common.user_group", record);
    CreateResourceRecordResponse response = client.createResourceRecord(request);
    System.out.println("[create user group]" + JSON.toJSONString(response));
}

Manage webhook integration

private static void createWebhookIntegration() throws LogException {
    ResourceWebhookIntegration dingtalk = new ResourceWebhookIntegration();
    dingtalk.setId("dingtalk");
    dingtalk.setName("Dingtalk Webhook");
    dingtalk.setMethod("POST");
    dingtalk.setUrl("https://oapi.dingtalk.com/robot/send?access_token=**********");
    dingtalk.setType("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. 
    // dingtalk.setSecret("SEC**********");
    dingtalk.setHeaders(Collections.<ResourceWebhookIntegration.Header>emptyList());

    ResourceWebhookIntegration wechat = new ResourceWebhookIntegration();
    wechat.setId("wechat");
    wechat.setName("Wechat Webhook");
    wechat.setMethod("POST");
    wechat.setUrl("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=**********");
    wechat.setType("wechat");
    wechat.setHeaders(Collections.<ResourceWebhookIntegration.Header>emptyList());

    ResourceWebhookIntegration feishu = new ResourceWebhookIntegration();
    feishu.setId("feisu");
    feishu.setName("Feishu Webhook");
    feishu.setMethod("POST");
    feishu.setUrl("https://open.feishu.cn/open-apis/bot/v2/hook/**********");
    feishu.setType("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. 
    // feishu.setSecret("**********");
    feishu.setHeaders(Collections.<ResourceWebhookIntegration.Header>emptyList());

    ResourceWebhookIntegration slack = new ResourceWebhookIntegration();
    slack.setId("slack");
    slack.setName("Slack Webhook");
    slack.setMethod("POST");
    slack.setUrl("https://hooks.slack.com/services/**********");
    slack.setType("slack");
    slack.setHeaders(Collections.<ResourceWebhookIntegration.Header>emptyList());

    ResourceWebhookIntegration webhook = new ResourceWebhookIntegration();
    webhook.setId("webhook");
    webhook.setName("Common Webhook");
    webhook.setMethod("POST");
    webhook.setUrl("https://example.com/***********");
    webhook.setType("custom");
    ResourceWebhookIntegration.Header authHeader = new ResourceWebhookIntegration.Header();
    authHeader.setKey("Authorization");
    authHeader.setValue("Basic YWRtaW46Zm9vYmFy");
    webhook.setHeaders(Collections.singletonList(authHeader));

    ResourceWebhookIntegration[] webhooks = {dingtalk, wechat, feishu, slack, webhook};
    for (ResourceWebhookIntegration webhookIntegration: webhooks) {
        ResourceRecord record = new ResourceRecord();
        record.setId(webhookIntegration.getId());
        record.setTag(webhookIntegration.getName());
        record.setValue(JSON.toJSONString(webhookIntegration));

        CreateResourceRecordRequest request = new CreateResourceRecordRequest("sls.alert.action_webhook", record);
        CreateResourceRecordResponse response = client.createResourceRecord(request);
        System.out.println("[create webhook integration] " + record.getId() + " " + JSON.toJSONString(response));
    }
}

Manage action policies

private static void createActionPolicy() throws LogException {
    ResourceActionPolicy actionPolicy = new ResourceActionPolicy();
    actionPolicy.setActionPolicyId("test-action-policy");
    actionPolicy.setActionPolicyName("Test Action Policy");
    actionPolicy.setPrimaryPolicyScript("fire(type=\"sms\", users=[\"alex\"], groups=[], oncall_groups=[], receiver_type=\"static\", external_url=\"\", external_headers={}, template_id=\"sls.builtin.cn\", period=\"any\")");
    actionPolicy.setSecondaryPolicyScript("fire(type=\"voice\", users=[\"alex\"], groups=[], oncall_groups=[], receiver_type=\"static\", external_url=\"\", external_headers={}, template_id=\"sls.builtin.cn\", period=\"any\")");
    actionPolicy.setEscalationStartEnabled(false);
    actionPolicy.setEscalationStartTimeout("10m");
    actionPolicy.setEscalationInProgressEnabled(false);
    actionPolicy.setEscalationInProgressTimeout("30m");
    actionPolicy.setEscalationEnabled(true);
    actionPolicy.setEscalationTimeout("1h");

    ResourceRecord record = new ResourceRecord();
    record.setId(actionPolicy.getActionPolicyId());
    record.setTag(actionPolicy.getActionPolicyName());
    record.setValue(JSON.toJSONString(actionPolicy));

    CreateResourceRecordRequest request = new CreateResourceRecordRequest("sls.alert.action_policy", record);
    CreateResourceRecordResponse response = client.createResourceRecord(request);
    System.out.println("[create action policy]" + JSON.toJSONString(response));
}

Manage alert policies

private static void createAlertPolicy() throws LogException {
    ResourceAlertPolicy alertPolicy = new ResourceAlertPolicy();
    alertPolicy.setPolicyId("test-alert-policy");
    alertPolicy.setPolicyName("Test Alert Policy");
    alertPolicy.setParentId("");
    alertPolicy.setGroupScript("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\")");
    alertPolicy.setInhibitScript("");
    alertPolicy.setSilenceScript("");

    ResourceRecord record = new ResourceRecord();
    record.setId(alertPolicy.getPolicyId());
    record.setTag(alertPolicy.getPolicyName());
    record.setValue(JSON.toJSONString(alertPolicy));

    CreateResourceRecordRequest request = new CreateResourceRecordRequest("sls.alert.alert_policy", record);
    CreateResourceRecordResponse response = client.createResourceRecord(request);
    System.out.println("[create alert policy]" + JSON.toJSONString(response));
}

Manage alert templates

private static void createContentTemplate() throws LogException {
    ResourceContentTemplate.Template sms = new ResourceContentTemplate.Template();
    sms.setLocale("zh-CN");
    sms.setContent("");

    ResourceContentTemplate.Template voice = new ResourceContentTemplate.Template();
    voice.setLocale("zh-CN");
    voice.setContent("");

    ResourceContentTemplate.Template email = new ResourceContentTemplate.Template();
    email.setLocale("en-US");
    email.setSubject("SLS Alert");
    email.setContent("");

    ResourceContentTemplate.Template dingtalk = new ResourceContentTemplate.Template();
    dingtalk.setLocale("zh-CN");
    dingtalk.setTitle("SLS Alert");
    dingtalk.setContent("");

    ResourceContentTemplate.Template wechat = new ResourceContentTemplate.Template();
    wechat.setLocale("zh-CN");
    wechat.setTitle("SLS Alert");
    wechat.setContent("");

    ResourceContentTemplate.Template lark = new ResourceContentTemplate.Template();
    lark.setLocale("zh-CN");
    lark.setTitle("SLS Alert");
    lark.setContent("");

    ResourceContentTemplate.Template slack = new ResourceContentTemplate.Template();
    slack.setLocale("zh-CN");
    slack.setTitle("SLS Alert");
    slack.setContent("");

    ResourceContentTemplate.Template webhook = new ResourceContentTemplate.Template();
    webhook.setLocale("zh-CN");
    webhook.setSendType("single");
    webhook.setLimit(0);
    webhook.setContent("");

    ResourceContentTemplate.Templates templates = new ResourceContentTemplate.Templates();
    templates.setSms(sms);
    templates.setVoice(voice);
    templates.setEmail(email);
    templates.setDingtalk(dingtalk);
    templates.setWechat(wechat);
    templates.setLark(lark);
    templates.setSlack(slack);
    templates.setWebhook(webhook);

    String templateId = "test-template";
    String templateName = "Test Template";
    Map<String, Object> contentTemplate = new HashMap<String, Object>();
    contentTemplate.put("template_id", templateId);
    contentTemplate.put("template_name", templateName);
    contentTemplate.put("templates", templates);

    ResourceRecord record = new ResourceRecord();
    record.setId(templateId);
    record.setTag(templateName);
    record.setValue(JSON.toJSONString(contentTemplate));

    CreateResourceRecordRequest request = new CreateResourceRecordRequest("sls.alert.content_template", record);
    CreateResourceRecordResponse response = client.createResourceRecord(request);
    System.out.println("[create content template]" + JSON.toJSONString(response));
}

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.