Ends in
00
days
00
hrs
00
mins
00
secs
ENROLL NOW

Get any AWS Specialty Mock Test for FREE when you Buy 2 AWS Pro-Level Practice Tests – as LOW as $10.49 USD each ONLY!

Instrumenting your Application with AWS X-Ray

Home » AWS Cheat Sheets » AWS Developer Tools » Developer Related Notes » Instrumenting your Application with AWS X-Ray

Instrumenting your Application with AWS X-Ray

Last updated on August 14, 2023

Instrumenting your Node.js application

  1. The AWS X-Ray SDK for Node.js provides middleware that you can use to instrument incoming HTTP requests. You need to add the SDK to your application’s dependencies, usually via package.json.
  2. Initialize the SDK client and add it to your application prior to declaring routes.
var AWSXRay = require('aws-xray-sdk');
AWSXRay.setDaemonAddress('host:port');
app.use(AWSXRay.express.openSegment('MyApp')); 

      3. Lastly, use the SDK exceptions after declaring routes.

Tutorials dojo strip
app.get('/', function (req, res) {
  res.render('index');
});
app.use(AWSXRay.express.closeSegment());

Instrumenting your Java application

The AWS X-Ray SDK for Java provides a servlet filter that you can add to your application to start tracing incoming HTTP requests. First, if you are using Maven and Tomcat, you need to add the SDK as a dependency in your build configuration.

    1. Starting in release 1.3, you can instrument your application using aspect-oriented programming (AOP) in Spring. What this means is that you can instrument your application, while it is running on AWS, without adding any code to your application’s runtime.
*in a pom.xml file*
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-xray-recorder-sdk-core</artifactId>
  <version>version</version>
</dependency>

                 2. Add a servlet filter to your deployment descriptor to trace incoming HTTP requests.

*in a web.xml file*
<filter>
  <filter-name>AWSXRayServletFilter</filter-name>
  <filter-class>com.amazonaws.xray.javax.servlet.AWSXRayServletFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>AWSXRayServletFilter</filter-name>
  <url-pattern>*</url-pattern>
</filter-mapping>

Instrumenting your C# .Net application

  1. The AWS X-Ray SDK for .NET provides a message handler that you can add to your HTTP configuration to trace incoming HTTP requests. Add the AWSXRayRecorder package to your application with NuGet.
  2. Add the message handler to your HTTP configuration.
using Amazon.XRay.Recorder.Handler.Http;
public static class AppConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new TracingMessageHandler());
    }
}

Instrumenting your Python application

  1. The X-Ray SDK for Python is a library for web applications that provides classes and methods for generating and sending trace data to the X-Ray daemon. You first download the SDK with pip.
pip install aws-xray-sdk

      2. Add the Python (Django, Flask, etc) middleware to your code to instrument incoming HTTP requests.

Instrumenting your Go application

  1. The X-Ray SDK for Go is a set of libraries for Go applications that provide classes and methods for generating and sending trace data to the X-Ray daemon. You first download the SDK with the go get command.
go get -u github.com/aws/aws-xray-sdk-go/...

      2. Use xray.Handler to instrument incoming HTTP requests.

func main() {
  http.Handle("/", xray.Handler(xray.NewFixedSegmentNamer(appname), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World!"))
  })))  
  http.ListenAndServe(":8000", nil)
}

To avoid calling the service every time your application serves a request, the SDK sends the trace data to an X-Ray daemon, which collects segments for multiple requests and uploads them in batches. Use the following scripts to automatically install a daemon to your AWS host:

  1. Linux EC2
#!/bin/bash
curl https://s3.dualstack.us-east-1.amazonaws.com/aws-xray-assets.us-east-
1/xray-daemon/aws-xray-daemon-2.x.rpm -o /home/ec2-user/xray.rpm
yum install -y /home/ec2-user/xray.rpm

      2. Windows EC2

<powershell>
if ( Get-Service "AWSXRayDaemon" -ErrorAction SilentlyContinue ) {
    sc.exe stop AWSXRayDaemon
    sc.exe delete AWSXRayDaemon
}
$targetLocation = "C:\Program Files\Amazon\XRay"
if ((Test-Path $targetLocation) -eq 0) {
    mkdir $targetLocation
}
$zipFileName = "aws-xray-daemon-windows-service-2.x.zip"
$zipPath = "$targetLocation\$zipFileName"
$destPath = "$targetLocation\aws-xray-daemon"
if ((Test-Path $destPath) -eq 1) {
    Remove-Item -Recurse -Force $destPath
}
$daemonPath = "$destPath\xray.exe"
$daemonLogPath = "$targetLocation\xray-daemon.log"
$url = 

"https://s3.dualstack.us-east-1.amazonaws.com/aws-xray-assets.us-east-
1/xray-daemon/aws-xray-daemon-windows-service-2.x.zip"
Invoke-WebRequest -Uri $url -OutFile $zipPath
Add-Type -Assembly "System.IO.Compression.Filesystem"
[io.compression.zipfile]::ExtractToDirectory($zipPath, $destPath)
New-Service -Name "AWSXRayDaemon" -StartupType Automatic 
-BinaryPathName "`"$daemonPath`" -f `"$daemonLogPath`""
sc.exe start AWSXRayDaemon
</powershell>

       3. ECS

                  a. You can simply pull the Docker image that you can deploy alongside your application.

docker pull amazon/aws-xray-daemon

                  b. Or create a folder and download the daemon.

mkdir xray-daemon && cd xray-daemon
curl https://s3.dualstack.us-east-1.amazonaws.com/aws-xray-assets.us
-east-1/xray-daemon/aws-xray-daemon-linux-2.x.zip -o 
./aws-xray-daemon-linux-2.x.zip
~/xray-daemon$ unzip -o aws-xray-daemon-linux-2.x.zip -d .

                  c. Then, create a Dockerfile with the following content.

*~/xray-daemon/Dockerfile*
FROM ubuntu:version
COPY xray /usr/bin/xray-daemon
CMD xray-daemon -f /var/log/xray-daemon.log &

                 d. Finally, build the image with docker build

docker build -t xray 

       4. Elastic Beanstalk

    • X-Ray daemon is already built-in in Elastic Beanstalk. Enable it through a configuration file placed under ebextensions or through the console settings.
# .ebextensions/xray-daemon.config
option_settings:
  aws:elasticbeanstalk:xray:
    XRayEnabled: true

      5. Lambda

    • X-Ray automatically runs in the background when you enable tracing for your functions.

 

References:

https://us-east-1.console.aws.amazon.com/xray/home?region=us-east-1#/getting-started
https://docs.aws.amazon.com/xray/latest/devguide/xray-daemon.html

Get any AWS Specialty Mock Test for FREE when you Buy 2 AWS Pro-Level Practice Tests – as LOW as $10.49 USD each ONLY!

Tutorials Dojo portal

Learn AWS with our PlayCloud Hands-On Labs

Tutorials Dojo Exam Study Guide eBooks

tutorials dojo study guide eBook

FREE AWS Exam Readiness Digital Courses

Subscribe to our YouTube Channel

Tutorials Dojo YouTube Channel

FREE AWS, Azure, GCP Practice Test Samplers

Follow Us On Linkedin

Recent Posts

Written by: Jon Bonso

Jon Bonso is the co-founder of Tutorials Dojo, an EdTech startup and an AWS Digital Training Partner that provides high-quality educational materials in the cloud computing space. He graduated from Mapúa Institute of Technology in 2007 with a bachelor's degree in Information Technology. Jon holds 10 AWS Certifications and is also an active AWS Community Builder since 2020.

AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!

Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!

View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses

Our Community

~98%
passing rate
Around 95-98% of our students pass the AWS Certification exams after training with our courses.
200k+
students
Over 200k enrollees choose Tutorials Dojo in preparing for their AWS Certification exams.
~4.8
ratings
Our courses are highly rated by our enrollees from all over the world.

What our students say about us?