AWS X-ray with Django

Overview

In this article I will discuss how I configured my DjangoCMS site to use Amazon's X-ray.

Prerequisites

The following are required in order for you configure your Django app to use Amazon's X-ray.

  • AWS Account
  • EC2 Instance Profile and or Access Key / Secret Key
  • Django 1.10 and above installed
    **Note this is very important
  • Python3 and pip installed

Let's Get started

What is Amazon X-ray

The X-Ray SDK for Python is a library for Django and Flask web applications that provides classes and methods for generating and sending trace data to the X-Ray daemon. Trace data includes information about incoming HTTP requests served by the application, and calls that the application makes to downstream services using the AWS SDK, HTTP clients, or an SQL database connector. You can also create segments manually and add debug information in annotations and metadata.

Install Amazon X-ray

First things first we need to install Amazon x-ray.

pip install aws-xray-sdk

Configure Django App

Import Xray

In order to configure our Django App it must be Django 1.10 or greater. Let's modify our settings.py. Add the following

 

from aws_xray_sdk.core import xray_recorder

Configure Middleware

Next we need to add in our Xray recorder to our middle ware:

MIDDLEWARE = [
    'aws_xray_sdk.ext.django.middleware.XRayMiddleware',
    ....
]

Add to installed apps

INSTALLED_APPS = (
    'aws_xray_sdk.ext.django',
    ...,
)

Configure Xray

Configure recorder

Configuring the recorder can be done directly in the settings.py using the following form the AWS docs: http://docs.aws.amazon.com/xray/latest/devguide/xray-sdk-python-configuration.html

  • AUTO_INSTRUMENT (Django only) – Record subsegments for built-in database and template rendering operations.
  • AWS_XRAY_CONTEXT_MISSING – Set to LOG_ERROR to avoid throwing exceptions when your instrumented code attempts to record data when no segment is open.
  • AWS_XRAY_DAEMON_ADDRESS – Set the host and port of the X-Ray daemon listener.
  • AWS_XRAY_TRACING_NAME – Set a service name that the SDK uses for segments.
  • PLUGINS – Record information about your application's AWS resources.
  • SAMPLING – Set to False to disable sampling.
  • SAMPLING_RULES – Set the path of the JSON file containing your sampling rules.

My sample configuration is below:

# Xray configurations
XRAY_RECORDER = {
    'AUTO_INSTRUMENT': True,
    'AWS_XRAY_CONTEXT_MISSING': 'LOG_ERROR',
    'AWS_XRAY_TRACING_NAME': 'michaelTrottier20',
    'DYNAMIC_NAMING': '*.michaeltrottier.com',
    'PLUGINS': ('ElasticBeanstalkPlugin', 'EC2Plugin'),
    'SAMPLING': False,
}