เป้าหมาย
รู้ว่าระบบพังก่อนลูกค้าบอก: เก็บ log แบบมีโครงสร้าง ตั้ง retention, สร้าง metric และ alarm ที่ไม่ปลุกตอนตีสามโดยไม่จำเป็น, ค้น log ด้วย Logs Insights และตาม request ข้ามบริการด้วย tracing
3 เสาของ observability
| ตอบคำถาม | บน AWS | |
|---|---|---|
| Metrics | "ระบบป่วยไหม" (ตัวเลขตามเวลา) | CloudWatch Metrics, Embedded Metric Format (EMF) |
| Logs | "เกิดอะไรขึ้นกับ request นี้" | CloudWatch Logs, Logs Insights, Live Tail |
| Traces | "ช้าที่ hop ไหน" | X-Ray / OpenTelemetry, CloudWatch Application Signals, Transaction Search |
เริ่มจาก 4 golden signals ต่อทุก service: latency (p50/p99 ไม่ใช่ average), traffic, errors, saturation (เช่น concurrency, queue depth, CPU)
Logs: ทำให้ค้นได้และไม่แพง
- log เป็น JSON หนึ่งบรรทัดต่อ event มี
level,requestId,route,durationMs→ Logs Insights กรองตาม field ได้ทันที - ตั้ง retention ทุก log group — ค่าเริ่มต้นคือ ไม่มีวันหมดอายุ ค่าเก็บสะสมทุกเดือน
- อย่า log ข้อมูลลับ/PII (token, เลขบัตร) — ใช้ data protection policy ของ CloudWatch Logs mask ได้ แต่ดีที่สุดคือไม่ log ตั้งแต่แรก
- คิดเงินก่อนเปิด debug log ใน prod:
| ปริมาณ | คำนวณ |
|---|---|
| 1M request/วัน × 2 KB log | ≈ 2 GB/วัน ≈ 60 GB/เดือน |
| ค่า ingest ≈ $0.50/GB | ≈ $30/เดือน แค่ส่ง log — debug log 10 เท่าก็ $300 |
⚠️ ต้องตรวจสอบ: ราคา ingest log ~$0.50/GB (Standard), log class Infrequent Access ถูกกว่าราวครึ่ง, Logs Insights ~$0.005/GB ที่สแกน, custom metric ~$0.30/ตัว/เดือน, alarm ~$0.10/ตัว/เดือน — เป็นค่า us-east-1 ดูราคา region ของคุณที่ aws.amazon.com/cloudwatch/pricing
Metrics และ Alarms ที่ดี
- metric ของ AWS มีมาให้ฟรี (Lambda
Errors,Throttles,Duration,ConcurrentExecutions; SQSApproximateAgeOfOldestMessage; API Gateway5xx) - metric ธุรกิจ (เช่น
OrdersPlaced) ส่งด้วย EMF — พิมพ์ JSON ลง log แล้ว CloudWatch แตกเป็น metric ให้ ไม่ต้องเรียกPutMetricData - ระวัง dimension ที่ค่าไม่จำกัด (userId, requestId) — ทุกค่าที่ไม่ซ้ำ = custom metric ใหม่ 1 ตัว = บิลระเบิด
ส่วนประกอบของ alarm
| ค่า | ความหมาย | ตั้งอย่างไร |
|---|---|---|
period |
ช่วงรวมข้อมูล | 60 วินาทีสำหรับ API |
evaluation-periods / datapoints-to-alarm |
"M จาก N" | 3 จาก 5 ลด alarm กระพริบจาก spike เดียว |
treat-missing-data |
ไม่มีข้อมูลถือว่าอะไร | metric error ที่ไม่มี traffic → notBreaching · heartbeat → breaching |
| statistic | Sum / Average / p99 | latency ใช้ p99 (extended statistic) |
- alarm ที่ปลุกคนต้อง actionable — ถ้ารับแล้วทำอะไรไม่ได้ ให้ไปเป็น dashboard/ticket แทน
- composite alarm รวมหลาย alarm (เช่น "error สูง AND traffic > 0") ลดเสียงรบกวน
- คิดแบบ SLO: "99.9% ของ request สำเร็จใน 30 วัน" = error budget 43 นาที/เดือน แล้ว alarm ตาม อัตราการเผา budget แทน threshold มั่วๆ
Tracing: ไป OpenTelemetry
- X-Ray service ยังอยู่และพัฒนาต่อ แต่ X-Ray SDK และ daemon เข้า maintenance mode ตั้งแต่ 25 ก.พ. 2026 และหมดซัพพอร์ต 25 ก.พ. 2027
- งานใหม่ instrument ด้วย OpenTelemetry (เช่น AWS Distro for OpenTelemetry — ADOT) แล้วส่ง trace เข้า X-Ray/CloudWatch ได้เหมือนเดิม
- Lambda เปิด active tracing ได้ด้วย
aws lambda update-function-configuration --tracing-config Mode=Activeเพื่อดูเวลาของ invocation เบื้องต้น
ลองเลย 🧪
ใช้ stack NotesApi-dev จากบท 02 (deploy ไว้ก่อน) · ⚠️ alarm 1 ตัว + SNS email แทบไม่มีค่าใช้จ่าย แต่ลบตอนจบ
aws sso login --profile dev
export AWS_PROFILE=dev AWS_REGION=ap-southeast-1
FN=$(aws cloudformation describe-stack-resources --stack-name NotesApi-dev \
--query "StackResources[?ResourceType=='AWS::Lambda::Function'].PhysicalResourceId" --output text)
LG=$(aws lambda get-function-configuration --function-name "$FN" --query LoggingConfig.LogGroup --output text)
URL=$(aws cloudformation describe-stacks --stack-name NotesApi-dev \
--query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" --output text)
echo "$FN | $LG"ทดลอง A — หา log group ที่ไม่มี retention ทั้งบัญชี
aws logs describe-log-groups \
--query "logGroups[?!retentionInDays].[logGroupName,storedBytes]" --output table→ ทุกแถวที่ขึ้นคือเงินที่จ่ายไปตลอดกาล ตั้งให้ด้วย (ตัวอย่าง 30 วัน):
aws logs put-retention-policy --log-group-name "[ชื่อ log group]" --retention-in-days 30ทดลอง B — สร้าง traffic แล้วดู log สด
for i in $(seq 1 20); do curl -s -o /dev/null -w "%{http_code} " "$URL/notes"; done; echo
curl -s -o /dev/null -w "%{http_code}\n" -X POST "$URL/notes" -d 'not-json'
aws logs tail "$LG" --since 10m --format short | tail -5ผลที่ควรเห็น: 200 20 ครั้ง ตามด้วย 500 (body ไม่ใช่ JSON ทำให้ JSON.parse พัง) และใน log มีบรรทัด ERROR Invoke Error ... SyntaxError
ทดลอง C — Logs Insights หา error และ latency
QID=$(aws logs start-query --log-group-name "$LG" \
--start-time $(( $(date +%s) - 3600 )) --end-time $(date +%s) \
--query-string 'filter @type = "REPORT"
| stats count() as invocations, avg(@duration) as avgMs, pct(@duration, 99) as p99Ms, max(@maxMemoryUsed/1000/1000) as maxMemMB' \
--query queryId --output text)
sleep 5
aws logs get-query-results --query-id "$QID" --query "results" --output jsonผลที่ควรเห็น: ตัวเลข invocations ≈ 21, avgMs, p99Ms (cold start ทำให้ p99 สูงกว่า avg มาก — นี่คือเหตุผลที่ต้องดู percentile)
ลองอีก query: fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 5
ทดลอง D — alarm บน Lambda Errors ส่งอีเมล
TOPIC=$(aws sns create-topic --name notes-alarms --query TopicArn --output text)
aws sns subscribe --topic-arn "$TOPIC" --protocol email --notification-endpoint "[[email protected]]"
# เปิดอีเมลแล้วกด Confirm subscription ก่อนไปต่อ
aws cloudwatch put-metric-alarm --alarm-name notes-dev-errors \
--namespace AWS/Lambda --metric-name Errors --dimensions Name=FunctionName,Value="$FN" \
--statistic Sum --period 60 --evaluation-periods 5 --datapoints-to-alarm 3 \
--threshold 1 --comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching --alarm-actions "$TOPIC" --ok-actions "$TOPIC"
# ทดสอบ notification โดยไม่ต้องรอ error จริง
aws cloudwatch set-alarm-state --alarm-name notes-dev-errors \
--state-value ALARM --state-reason "manual test"
aws cloudwatch describe-alarms --alarm-names notes-dev-errors --query "MetricAlarms[0].StateValue" --output textผลที่ควรเห็น: อีเมล ALARM: "notes-dev-errors" ภายในไม่กี่วินาที และ state เป็น ALARM (นาทีถัดไปจะกลับ OK เองเพราะ metric จริงไม่ถึง threshold)
ทดลอง E — metric ธุรกิจด้วย EMF (วางใน handler ของบท 02 ตรงจุดที่ POST สำเร็จ แล้ว deploy)
console.log(JSON.stringify({
_aws: {
Timestamp: Date.now(),
CloudWatchMetrics: [{ Namespace: "NotesApi", Dimensions: [["Stage"]], Metrics: [{ Name: "NotesCreated", Unit: "Count" }] }],
},
Stage: process.env.STAGE,
NotesCreated: 1,
}));→ หลัง POST ไม่กี่ครั้ง ดู aws cloudwatch list-metrics --namespace NotesApi จะเห็น NotesCreated (Dimension มีแค่ Stage — ห้ามใส่ userId)
เก็บกวาด
aws cloudwatch delete-alarms --alarm-names notes-dev-errors
aws sns delete-topic --topic-arn "$TOPIC"
# ถ้าไม่ใช้ stack ต่อแล้ว (รันในโฟลเดอร์ notes-api)
npx cdk destroy -c stage=dev --force(ถ้าเปิดเทอร์มินัลใหม่ $TOPIC จะหาย — ใช้ aws sns list-topics --query "Topics[?ends_with(TopicArn, ':notes-alarms')].TopicArn" --output text)
ถ้าพัง: LG ว่าง → function ไม่ได้ตั้ง logGroup ใช้ /aws/lambda/$FN แทน · query คืน [] → รอ log เข้าอีกครู่หรือขยาย start-time · ไม่ได้อีเมล → ยังไม่ confirm subscription
กับดักที่เจอบ่อย
| อาการ | สาเหตุ / แก้ |
|---|---|
| บิล CloudWatch สูงกว่า Lambda | log มากเกิน + ไม่มี retention — ลด log level ใน prod, ตั้ง retention, พิจารณา Infrequent Access class |
| custom metric นับพันตัว | dimension ใช้ค่าไม่จำกัด (userId, URL เต็ม) — ใช้ค่าคงที่จำนวนน้อย |
| alarm ดังตลอดแล้วทีมเลิกสนใจ | threshold จาก spike เดียว — ใช้ M-of-N, composite, และลบ alarm ที่ไม่ actionable |
| alarm เงียบตอนระบบตายสนิท | ไม่มี traffic = ไม่มี datapoint + notBreaching — เพิ่ม alarm ฝั่ง traffic/heartbeat ที่ breaching |
| ดู average latency แล้วสบายใจ | ผู้ใช้ 1% เจอช้ามาก — ดู p99 |
| ใช้ X-Ray SDK ในโปรเจกต์ใหม่ | SDK กำลังหมดซัพพอร์ต — ใช้ OpenTelemetry/ADOT |
สรุปจำง่าย
Metrics บอกว่าป่วย Logs บอกว่าเกิดอะไร Traces บอกว่าช้าที่ไหน — log เป็น JSON + ตั้ง retention เสมอ — alarm ต้อง actionable ใช้ M-of-N และ p99 — dimension ห้ามไม่จำกัด — tracing ใหม่ใช้ OpenTelemetry