如何基于CloudWatch Logs Insights查询设置告警及自定义指标?
Creating Log-Based Custom Metrics & Alarms in CloudWatch
Got it, let's break down exactly how to build those log-based custom metrics and set up alarms for them in CloudWatch—since you already have the dashboard part covered, we'll focus on the two key steps you need:
Step 1: Generate a Custom Metric from Your Log Query
First, turn your targeted log query into a reusable metric:
- Open the CloudWatch console, head to Logs > Logs Insights
- Select the log group(s) you want to analyze, then write your custom query. For example, if you're counting errors every 5 minutes:
filter @message like /ERROR/ | stats count(*) as ErrorCount by bin(5m) - Run the query to confirm it returns the data you expect
- Click the Export to metric button at the top right of the results panel
- Fill in the metric details carefully:
- Metric namespace: Use an existing one or create a new, meaningful one (e.g.,
MyApplication/LogMetrics) - Metric name: Pick a clear, specific name (e.g.,
ProductionErrorCount_5Min) - Dimensions: Add dimensions like
Environment=Productionto make filtering easier later - Statistic: Match this to your query—for
count(*), chooseSum
- Metric namespace: Use an existing one or create a new, meaningful one (e.g.,
- Review everything and click Create metric. Your new log-based metric will now appear in CloudWatch Metrics.
Step 2: Set Up an Alarm for Your Custom Metric
Now let's make sure you get alerted when this metric crosses your threshold:
- Navigate to CloudWatch > Alarms > All alarms, then click Create alarm
- Under Specify metric, search for your custom metric using its namespace, name, or dimensions. Select it, then choose the same stat and period you used when creating the metric (e.g., Sum over 5 minutes)
- Click Next to define your alarm conditions:
- Choose between static or anomaly detection thresholds (static is most common for fixed limits)
- Set your threshold rule—for example: "Whenever ProductionErrorCount_5Min is greater than 10"
- Adjust evaluation periods (e.g., "Alarm if 2 out of the last 3 periods meet the threshold") to cut down on false alarms
- Click Next to configure alert actions:
- Add a notification: Select an existing SNS topic (or create a new one) to send alerts via email, SMS, or other channels
- Optional: Add auto-remediation actions (like restarting a service) if you have automation set up
- Give your alarm a descriptive name and description (e.g., "High Error Rate in Production API") so you know exactly what's triggering it at a glance
- Review all settings and click Create alarm
Quick Pro Tip
Once your alarm is live, you can add it to your existing CloudWatch Dashboard by editing the dashboard and adding an Alarm Status Widget—this ties your metrics, logs, and alerts together for full operational visibility, just like you wanted.
内容的提问来源于stack exchange,提问作者jimmone
相关产品推荐
相关产品推荐

