Integrating AWS Xray with Loopback
Last updated on

Integrating AWS Xray with Loopback


AWS Xray and Loopback

AWS Xray is a service that helps you trace requests throughout a distributed application on AWS, and Loopback is a Node.js API framework, for quick and easy API building.

I added Xray to a loopback application (running on Elasticbeanstalk) and I couldn’t find any particular guidance on the correct way to do it. What I did is working, so I figured I would share.

How

I had to edit a single file in the loopback application and add a file to the deployment configuration to set up the server daemon to get this working, so it’s pretty simple.

1) Install AWS Xray package

# Install aws-xray-sdk
npm i aws-xray-sdk --save

2) Update server/server.js

All that’s required to get this working is requiring the module and then a few lines added to server.js, before starting the app.

AWSXRay.config([
  AWSXRay.plugins.EC2Plugin, // Add the EC2 plugin
  AWSXRay.plugins.ElasticBeanstalkPlugin, // If using Elastic beanstalk add the Elastic beanstalk plugin
])
// Because Loopback is based on express, we can just use the express middleware.
AWSXRay.express.openSegment('')
AWSXRay.express.closeSegment()
var loopback = require('loopback')
var boot = require('loopback-boot')
var app = (module.exports = loopback())

// Require the module
var AWSXray = require('aws-xray-sdk')

AWSXRay.config([
  AWSXRay.plugins.EC2Plugin, // Add the EC2 plugin
  AWSXRay.plugins.ElasticBeanstalkPlugin, // If using Elastic beanstalk add the Elastic beanstalk plugin
])

// Register openSegment as soon as possible
// and register a default trace name
app.use(AWSXRay.express.openSegment('myTraceName'))
// Register closeSegment as middleware.
// Register it in the routes:after phase so that it's
// called after all route processing
app.middleware('routes:after', AWSXRay.express.closeSegment())

app.start = function () {
  return app.listen(function () {
    app.emit('started')
    var baseUrl = app.get('url').replace(/\/$/, '')
    console.log('Web server listening at: %s', baseUrl)
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath)
    }
  })
}

boot(app, __dirname, function (err) {
  if (err) throw err
  if (require.main === module) app.start()
})

3) Add file to .ebextensions/

This file will setup the Xray daemon on the EC2 instance. The daemon collects segments for multiple requests and updates the AWS Xray service with them in batches.

# .ebextensions/xray-daemon.config
option_settings:
  aws:elasticbeanstalk:xray:
    XRayEnabled: true

You can find information for other daemon setups @

That’s it

Theres more advanced things you can do with Xray and a lot more configuration options, I was mainly interested in testing it out and having a look around the service. You can find more information in the AWS Xray developer guide