| PutMetricData | EMF | |
|---|---|---|
| Method | API call | Structured log |
| Cost | Per API call ($) | Free (log ingestion only) |
| Latency | Extra network call | No extra call |
| Best for | EC2, ECS | Lambda, ephemeral resources |
Lợi ích:
import json
def handler(event, context):
print(json.dumps({
"_aws": {
"Timestamp": 1705312200000,
"CloudWatchMetrics": [{
"Namespace": "MyApp",
"Dimensions": [["Service", "Environment"]],
"Metrics": [
{"Name": "OrderProcessingTime", "Unit": "Milliseconds"},
{"Name": "OrderCount", "Unit": "Count"}
]
}]
},
"Service": "OrderService",
"Environment": "prod",
"OrderProcessingTime": 150,
"OrderCount": 1
}))
from aws_lambda_powertools import Metrics
from aws_lambda_powertools.metrics import MetricUnit
metrics = Metrics(namespace="MyApp", service="OrderService")
@metrics.log_metrics(capture_cold_start_metric=True)
def handler(event, context):
metrics.add_metric(name="OrdersProcessed", unit=MetricUnit.Count, value=1)
Scenario thi: Tạo shared dashboard trong CloudWatch để monitor 5 applications khác nhau.
Giải pháp:
Lưu ý: Không có default namespace, bạn phải specify namespace khi tảo metric publish lên CloudWatch.
Exam Tip: