日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

使用Java SDK管理告警

本文介紹通過Java SDK使用日志服務(wù)告警功能的代碼示例。

前提條件

  • 已開通日志服務(wù)。更多信息,請參見開通日志服務(wù)

  • 已創(chuàng)建RAM用戶并完成授權(quán)。具體操作,請參見創(chuàng)建RAM用戶并完成授權(quán)

  • 已配置環(huán)境變量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具體操作,請參見在Linux、macOS和Windows系統(tǒng)配置環(huán)境變量

    重要
    • 阿里云賬號的AccessKey擁有所有API的訪問權(quán)限,建議您使用RAM用戶的AccessKey進行API訪問或日常運維。

    • 強烈建議不要把AccessKey ID和AccessKey Secret保存到工程代碼里,否則可能導(dǎo)致AccessKey泄露,威脅您賬號下所有資源的安全。

  • 已安裝0.6.100及以上版本的日志服務(wù)SDK。具體操作,請參見安裝Java SDK

告警監(jiān)控規(guī)則管理

代碼示例如下。具體的參數(shù)說明,請參見告警監(jiān)控規(guī)則數(shù)據(jù)結(jié)構(gòu)

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 {
    // 設(shè)置日志服務(wù)的服務(wù)接入點。
    private static final String ENDPOINT = "cn-huhehaote.log.aliyuncs.com";
    // 本示例從環(huán)境變量中獲取AccessKey ID和AccessKey Secret。
    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");
    // 創(chuàng)建日志服務(wù)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();
    }
}
            

資源數(shù)據(jù)管理

代碼示例如下。具體的參數(shù)說明,請參見告警資源數(shù)據(jù)結(jié)構(gòu)

管理用戶

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 {
    
    // 設(shè)置日志服務(wù)的服務(wù)接入點。
    // 資源數(shù)據(jù)的寫操作,必須使用河源地域,讀操作可以使用其它地域。
    private static final String ENDPOINT = "cn-heyuan.log.aliyuncs.com";
    // 本示例從環(huán)境變量中獲取AccessKey ID和AccessKey Secret。
    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();
    }
}
            

管理用戶組

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

管理Webhook集成

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");
    // 釘釘加簽密鑰。如果您在釘釘側(cè)設(shè)置安全驗證方式為簽名校驗,則需配置該字段。您可以在釘釘機器人管理界面獲取加簽密鑰。
    // 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");
    // 飛書加簽密鑰。如果您在飛書側(cè)設(shè)置安全驗證方式為簽名校驗,則需配置該字段。您可以在飛書機器人管理界面獲取加簽密鑰。
    // 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));
    }
}

管理行動策略

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

管理告警策略

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

管理內(nèi)容模板

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

相關(guān)文檔

  • 在調(diào)用API接口過程中,若服務(wù)端返回結(jié)果中包含錯誤信息,則表示調(diào)用API接口失敗。您可以參考API錯誤碼對照表查找對應(yīng)的解決方法。更多信息,請參見API錯誤處理對照表

  • 阿里云OpenAPI開發(fā)者門戶提供調(diào)試、SDK、示例和配套文檔。通過OpenAPI,您無需手動封裝請求和簽名操作,就可以快速對日志服務(wù)API進行調(diào)試。更多信息,請參見OpenAPI開發(fā)者門戶

  • 為滿足越來越多的自動化日志服務(wù)配置需求,日志服務(wù)提供命令行工具CLI(Command Line Interface)。更多信息,請參見日志服務(wù)命令行工具CLI

  • 更多示例代碼,請參見Aliyun Log Java SDK on GitHub