iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CloudWatch

CloudWatch is AWS’s monitoring and observability stack. Logs, Metrics, Alarms, Dashboards, Insights queries, distributed traces (X-Ray). Most services emit there by default; your code just adds custom signals.

Logs, metrics, alarms, queries

EXAMPLE
# 1) Logs — every Lambda / ECS / EKS / EC2 with the agent already writes here
aws logs tail /aws/lambda/my-fn --follow
aws logs tail /aws/lambda/my-fn --since 1h --filter-pattern 'ERROR'

# Send custom logs (from app code)
import { CloudWatchLogsClient, PutLogEventsCommand } from '@aws-sdk/client-cloudwatch-logs';
// Most code instead logs to stdout and lets the runtime forward it.

# 2) Logs Insights — SQL-like queries
aws logs start-query --log-group-name '/aws/lambda/my-fn' \
    --start-time $(date -d '-1 hour' +%s) --end-time $(date +%s) \
    --query-string \
    'fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 50'

# 3) Metrics — built-in (Invocations, Duration, Errors) + custom
aws cloudwatch put-metric-data \
    --namespace MyApp \
    --metric-data \
    MetricName=Signups,Value=1,Unit=Count,Dimensions=Plan=Pro \
    MetricName=CheckoutDuration,Value=312,Unit=Milliseconds,Dimensions=Plan=Pro

# 4) Alarms — alert humans when a metric goes bad
aws cloudwatch put-metric-alarm \
    --alarm-name HighLambdaErrors \
    --metric-name Errors --namespace AWS/Lambda --statistic Sum \
    --dimensions Name=FunctionName,Value=my-fn \
    --period 60 --evaluation-periods 5 --threshold 1 \
    --comparison-operator GreaterThanOrEqualToThreshold \
    --treat-missing-data notBreaching \
    --alarm-actions arn:aws:sns:us-east-1:123:on-call

# 5) Structured logs win Insights queries
#    Always log JSON. Then 'filter level = "error"' actually works.
console.log(JSON.stringify({
    level:   'error',
    msg:     'checkout failed',
    userId,
    orderId,
    err:     err.message,
}));

Why it matters

Structured (JSON) logs + CloudWatch Logs Insights gives you ad-hoc analytics without an ELK stack. filter + stats by turns “why did checkout drop?” into a one-line query.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Logs + metrics + alarms.
aws logs tail /aws/lambda/my-fn --follow
Try it Yourself »

Exercise

Follow logs for a Lambda function.

aws logs tail /aws/lambda/fn

Discussion

Loading…