Monitoring and troubleshooting 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)
Once middleware is attached, all incoming requests are automatically traced.
# Instrument all supported libraries
from aws_xray_sdk.core import patch_all
patch_all()
# Or selectively
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]);
// Open segment for all incoming requests
app.use(xrayExpress.openSegment('MyExpressApp'));
app.get('/api/orders/:id', async (req, res) => {
const order = await fetchOrder(req.params.id);
res.json({ order });
});
// Close segment after response
app.use(xrayExpress.closeSegment());
// Automatic instrumentation
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() # instrument AWS SDK calls
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
|_ Application Container
| sends to xray-daemon:2000
|_ X-Ray Daemon Container
forwards to X-Ray service
xray_recorder.configure(
service='MyECSApp',
daemon_address='xray-daemon:2000'
)
amazon/aws-xray-daemon image, UDP port 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": "*"
}
Use the managed policy AWSXRayDaemonWriteAccess
Attach to:
Without correct permissions, the daemon runs but silently fails to deliver segments.

patch_all(), manual with decorators and context managersAWSXRayDaemonWriteAccess IAM policyMonitoring and troubleshooting AWS