use of com.google.monitoring.v3.AlertPolicy in project java-monitoring by googleapis.
the class CreateAlertPolicy method createAlertPolicy.
public static void createAlertPolicy(String projectId, String alertPolicyName) throws ApiException, IOException {
// once, and can be reused for multiple requests.
try (AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.create()) {
ProjectName name = ProjectName.of(projectId);
String metricType = "compute.googleapis.com/instance/cpu/utilization";
String resourceType = "gce_instance";
// A Filter that identifies which time series should be compared with the threshold
String metricFilter = "metric.type=" + '"' + metricType + '"' + " AND " + "resource.type=" + '"' + resourceType + '"';
// Build Duration
Duration aggregationDuration = Duration.newBuilder().setSeconds(60).build();
// Build Aggregation
Aggregation aggregation = Aggregation.newBuilder().setAlignmentPeriod(aggregationDuration).setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN).setPerSeriesAligner(Aggregation.Aligner.ALIGN_MAX).build();
// Build MetricThreshold
AlertPolicy.Condition.MetricThreshold metricThreshold = AlertPolicy.Condition.MetricThreshold.newBuilder().setComparison(ComparisonType.COMPARISON_GT).addAggregations(aggregation).setFilter(metricFilter).setDuration(aggregationDuration).build();
// Construct Condition object
AlertPolicy.Condition alertPolicyCondition = AlertPolicy.Condition.newBuilder().setDisplayName(alertPolicyName).setConditionThreshold(metricThreshold).build();
// Build an alert policy
AlertPolicy alertPolicy = AlertPolicy.newBuilder().setDisplayName(alertPolicyName).addConditions(alertPolicyCondition).setCombiner(AlertPolicy.ConditionCombinerType.AND).build();
// Create an alert policy
AlertPolicy actualAlertPolicy = alertPolicyServiceClient.createAlertPolicy(name, alertPolicy);
System.out.format("alert policy created:%s", actualAlertPolicy.getName());
}
}
Aggregations