AWS X-Ray Middleware for Express (Javascript)
npm install aws-xray-sdk-express* AWS X-Ray SDK Core (aws-xray-sdk-core)
* Express 4.14.0 or greater
The AWS X-Ray Express package automatically records information for incoming and outgoing
requests and responses, via the middleware functions in this package. To configure sampling,
dynamic naming, and more see the set up section.
The AWS X-Ray SDK Core has two modes - manual and automatic.
Automatic mode uses the cls-hooked package and automatically
tracks the current segment and subsegment. This is the default mode.
Manual mode requires that you pass around the segment reference.
In automatic mode, you can get the current segment/subsegment at any time:
var segment = AWSXRay.getSegment();
In manual mode, you can get the base segment off of the request object:
var segment = req.segment;
The X-Ray SDK provides two middlewares: AWSXRay.express.openSegment(
and AWSXRay.express.closeSegment(). These two middlewares must be used together
and wrap all of your defined routes that you'd like to trace.
In automatic mode, the openSegment middleware must be the last middleware added
before defining routes, and the closeSegment middleware must be the
first middleware added after defining routes. Otherwise issues with the cls-hooked
context may occur.
To get started with a functional express application instrumented with the X-Ray SDK, check out our sample app.
``js
var AWSXRay = require('aws-xray-sdk-core');
var xrayExpress = require('aws-xray-sdk-express');
var app = express();
//...
app.use(xrayExpress.openSegment('defaultName'));
app.get('/', function (req, res) {
var segment = AWSXRay.getSegment();
segment.addAnnotation('page', 'home');
//...
res.render('index');
});
app.get('/directory', function (req, res) {
var segment = AWSXRay.getSegment();
segment.addAnnotation('page', 'directory');
//...
res.render('directory');
});
app.use(xrayExpress.closeSegment());
`
`js
var AWSXRay = require('aws-xray-sdk-core');
var xrayExpress = require('aws-xray-sdk-express');
var app = express();
//...
var AWSXRay = require('aws-xray-sdk');
//Required at the start of your routes
app.use(xrayExpress.openSegment('defaultName'));
app.get('/', function (req, res) {
var segment = req.segment;
//...
res.render('index');
});
app.use(xrayExpress.closeSegment()); //Required at the end of your routes / first in error handling routes
``