AWS 监控与故障排查
John Q. Martin
Principal Consultant

from flask import Flask
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
app = Flask(__name__)
xray_recorder.configure(
service='MyFlaskApp',
sampling=True,
context_missing='LOG_ERROR',
daemon_address='127.0.0.1:2000'
)
XRayMiddleware(app, xray_recorder)
中间件接入后,所有入站请求都会自动跟踪。
# 为所有受支持的库埋点
from aws_xray_sdk.core import patch_all
patch_all()
# 或选择性埋点
from aws_xray_sdk.core import patch
patch(['boto3', 'requests', 'psycopg2'])

@xray_recorder.capture('process_order')
def process_order(order_id):
order = get_order(order_id)
return process_payment(order)
def process_order(order_id):
with xray_recorder.capture('fetch_order'):
order = db.query(Order).filter_by(
id=order_id).first()
with xray_recorder.capture('process_payment'):
return payment_service.charge(order.total)
xray_recorder.put_annotation(
'order_id', order_id)
xray_recorder.put_annotation(
'user_id', user_id)
xray_recorder.put_metadata(
'order_details',
{'items': order.items,
'total': order.total})
def process_order(order_id):
try:
order = get_order(order_id)
payment = process_payment(order)
return payment
except PaymentError as e:
xray_recorder.put_annotation(
'error_type', 'payment_failed')
xray_recorder.put_metadata(
'error_details',
{'message': str(e), 'order_id': order_id})
raise
const AWSXRay = require('aws-xray-sdk-core');
const xrayExpress = require('aws-xray-sdk-express');
const app = require('express')();
AWSXRay.config([AWSXRay.plugins.EC2Plugin]);
// 为所有入站请求打开分段
app.use(xrayExpress.openSegment('MyExpressApp'));
app.get('/api/orders/:id', async (req, res) => {
const order = await fetchOrder(req.params.id);
res.json({ order });
});
// 响应后关闭分段
app.use(xrayExpress.closeSegment());
// 自动埋点
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const https = AWSXRay.captureHTTPs(require('https'));
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all() # 为 AWS SDK 调用埋点
def lambda_handler(event, context):
xray_recorder.put_annotation(
'user_id', event['user_id'])
result = process_user(event['user_id'])
return {
'statusCode': 200,
'body': json.dumps(result)
}
Tracing: Active
ECS Task
|_ 应用容器
| 发送到 xray-daemon:2000
|_ X-Ray 守护进程容器
转发到 X-Ray 服务
xray_recorder.configure(
service='MyECSApp',
daemon_address='xray-daemon:2000'
)
amazon/aws-xray-daemon 镜像,UDP 端口 2000AWS_XRAY_DAEMON_ADDRESS=xray-daemon:2000sudo systemctl start xray
sudo systemctl enable xray
TotalBufferSizeMB: 24
Concurrency: 8
Region: "us-east-1"
Socket:
UDPAddress: "127.0.0.1:2000"
TCPAddress: "127.0.0.1:2000"
Logging:
LogLevel: "info"
LogPath: "/var/log/xray/xray-daemon.log"
LocalMode: false
{
"Effect": "Allow",
"Action": [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords",
"xray:GetSamplingRules",
"xray:GetSamplingTargets",
"xray:GetSamplingStatisticSummaries"
],
"Resource": "*"
}
使用托管策略 AWSXRayDaemonWriteAccess
附加到:
权限不正确时,守护进程会运行但无法投递分段且无提示。

patch_all() 自动埋点;用装饰器与上下文管理器手动埋点AWSXRayDaemonWriteAccess IAM 策略AWS 监控与故障排查