Instrument asyncio Python for distributed tracing with AWS X-Ray.

Overview

xraysink (aka xray-asyncio)

Package version Python versions Monthly downloads

Extra AWS X-Ray instrumentation to use distributed tracing with asyncio Python libraries that are not (yet) supported by the official aws_xray_sdk library.

Integrations Supported

  • Generic ASGI-compatible tracing middleware for any ASGI-compliant web framework. This has been tested with:
  • asyncio Task's
  • Background jobs/tasks

Installation

xraysink is distributed as a standard python package through pypi, so you can install it with your favourite Python package manager. For example:

pip install xraysink

How to use

xraysink augments the functionality provided by aws_xray_sdk. Before using the tools in xraysink, you first need to configure aws_xray_sdk - this will probably involve calling xray_recorder.configure() when your process starts, and optionally aws_xray_sdk.core.patch().

Extra instrumentation provided by xraysink is described below.

FastAPI

Instrument incoming requests in your FastAPI web server by adding the xray_middleware to your app. For example, you could do:

from starlette.middleware.base import BaseHTTPMiddleware
from xraysink.asgi.middleware import xray_middleware

# Standard asyncio X-Ray configuration, customise as you choose
xray_recorder.configure(context=AsyncContext(), service="my-cute-little-service")

# Create a FastAPI app with various middleware
app = FastAPI()
app.add_middleware(MyTracingDependentMiddleware)  # Any middleware that is added earlier will have the X-Ray tracing context available to it
app.add_middleware(BaseHTTPMiddleware, dispatch=xray_middleware)

Asyncio Tasks

If you start asyncio Task's from a standard request handler, then the AWS X-Ray SDK will not correctly instrument any outgoing requests made inside those Tasks.

Use the fixed AsyncContext from xraysink as a drop-in replacement, like so:

from aws_xray_sdk.core import xray_recorder
from xraysink.context import AsyncContext  # NB: Use the AsyncContext from xraysink

# Use the fixed AsyncContext when configuring X-Ray,
# and customise other configuration as you choose.
xray_recorder.configure(context=AsyncContext(use_task_factory=True))

Background Jobs/Tasks

If your process starts background tasks that make network calls (eg. to the database or an API in another service), then each execution of one of those tasks should be treated as a new X-Ray trace. Indeed, if you don't do so then you will likely get context_missing errors.

An async function that implements a background task can be easily instrumented using the @xray_task_async() decorator, like so:

from aws_xray_sdk.core import xray_recorder
from xraysink.tasks import xray_task_async

# Standard asyncio X-Ray configuration, customise as you choose
xray_recorder.configure(context=AsyncContext(), service="my-cute-little-service")

# Any call to this function will start a new X-Ray trace
@xray_task_async()
async def cleanup_stale_tokens():
    await database.get_table("tokens").delete(age__gt=1)

# Start your background task using your scheduling system of choice :)
schedule_recurring_task(cleanup_stale_tokens)

If your background task functions are called from a function that is already instrumented (eg. send an email immediately after handling a request), then the background task will appear as a child segment of that trace. In this case, you must ensure you use the fixed AsyncContext when configuring the recorder (ie. from xraysink.context import AsyncContext)

Process-Level Configuration

You can link your X-Ray traces to your CloudWatch Logs log records, which enhances the integration with AWS CLoudWatch ServiceLens. Take the following steps:

  1. Put the X-Ray trace ID into every log message. There is no convention for how to do this (it just has to appear verbatim in the log message somewhere), but if you are using structured logging then the convention is to use a field called traceId. Here's an example

    trace_id = xray_recorder.get_trace_entity().trace_id
    logging.getLogger("example").info("Hello World!", extra={"traceId": trace_id})
    
  2. Explicitly set the name of the CloudWatch Logs log group associated with your process. There is no general way to detect the Log Group from inside the process, hence it requires manual configuration as part of your process initialisation (eg. in the same place where you call xray_recorder.configure).

    set_xray_log_group("/example/service-name")
    

Note that this feature relies on undocumented functionality, and is not yet supported by the official Python SDK.

Licence

This project uses the Apache 2.0 licence, to make it compatible with aws_xray_sdk, the primary library for integrating with AWS X-Ray.

Owner
Gary Donovan
Two-Thirds-Stack developer across Python, Java and AWS. Infrastructure, server-side coding, and serverless.
Gary Donovan
Stack Overflow Error Parser

A python tool that executes python files and opens respective Stack Overflow threads in browser for errors encountered.

Raghavendra Khare 3 Jul 24, 2022
DEPRECATED - Official Python Client for the Discogs API

⚠️ DEPRECATED This repository is no longer maintained. You can still use a REST client like Requests or other third-party Python library to access the

Discogs 483 Dec 31, 2022
Programmeertheorie 2022 - Team Trainspotters - RailNL

Trainspotters Vak: Programmeertheorie 2022 Gekozen case: RailNL Teamnaam: Trainspotters Studenten: Mijntje Meijer, Sam Bijhouwer, Maik Larooij To-do's

Maik Larooij 1 Jan 25, 2022
NewpaperNews-API - Json data of the news with python

NewsAPI API Documentation BASE_URL = "https://saurav.tech/NewsAPI/" top_headline

Aryaman Prakash 2 Sep 23, 2022
Wanna play on the Overwatch NA servers?

OverwatchRegionSwapper-NA- Wanna play on the Overwatch NA servers? Use at you own risk. LIST OF IPs EU Netherlands: From: 5.42.168.0 to: 5.42.175.255

1 Jun 08, 2022
Pythonic wrapper for the Aladhan prayer times API.

aladhan.py is a pythonic wrapper for the Aladhan prayer times API. Installation Python 3.6 or higher is required. To Install aladhan.py with pip: pip

HETHAT 8 Aug 17, 2022
Sms-bomber - A Simple Browser Automated Bomber

A Simple Browser Automated Bomber which uses selenium :D Star the Repo and Follo

Terminal1337 9 Apr 11, 2022
Manage gmail account using python, forget about imap and just code what you supposed to do.

GGmail Manage gmail account using python, forget about imap and just code what you supposed to do. Help See documentation for more details. Install In

Dylan Do Amaral 6 Sep 23, 2022
A collection of scripts to steal BTC from Lightning Network enabled custodial services. Only for educational purpose! Share your findings only when design flaws are fixed.

Lightning Network Fee Siphoning Attack LN-fee-siphoning is a collection of scripts to subtract BTC from Lightning Network enabled custodial services b

Reckless_Satoshi 14 Oct 15, 2022
Telegram vc - A bot that can play music on telegram group's voice call

Telegram Voice Chat Bot A bot that can play music on telegram group's voice call

1 Jan 02, 2022
Telegram bot to stream videos in telegram voicechat for both groups and channels. Supports live strams, YouTube videos and telegram media.

Telegram VCVideoPlayBot An Telegram Bot By @ZauteKm To Stream Videos in Telegram Voice Chat. NOTE: Make sure you have started a VoiceChat in your Grou

Zaute 20 Oct 21, 2022
An EmbedBuilder in Python for discord.py embeds. Pip Module.

Discord.py-MaxEmbeds An EmbedBuilder for Discord bots in Python. You need discord.py to use this module. Installation Step 1 First you have to install

Max Tischberger 6 Jan 13, 2022
asyncio client for Deta Cloud

aiodeta Unofficial client for Deta Clound Install pip install aiodeta Supported functionality Deta Base Deta Drive Decorator for cron tasks Examples i

Andrii Leitsius 19 Feb 14, 2022
My beancount practice as a template

my-beancount-template 个人 Beancount 方案的模板仓库 相关博客 复式记账指北(一):What and Why? 复式记账指北(二):做账方法论 复式记账指北(三):如何打造不半途而废的记账方案 配置 详细配置请参考博客三。必须修改的配置有: Bot功能:data/be

KAAAsS 29 Nov 29, 2022
Auto file forward bot with python

Auto-File-Forward-Bot Auto file forward bot. Without Admin Permission in FROM_CHANNEL Only Give Permission In your Telegram Personal Channel Please fo

Milas 1 Oct 15, 2021
Leakvertise is a Python open-source project which aims to bypass these fucking annoying captchas and ads from linkvertise, easily

Leakvertise Leakvertise is a Python open-source project which aims to bypass these fucking annoying captchas and ads from linkvertise, easily. You can

Quatrecentquatre 9 Oct 06, 2022
Design and build a wrapper for the Open Weather API current weather data service

Design and build a wrapper for the Open Weather API current weather data service that returns a city's temperature, with caching, also allowing for the temperature of the latest queried cities that a

Duan Rafael Ribeiro 1 Jun 27, 2022
A discord bot thet lets you play Space invaders.

space_Invaders A discord bot thet lets you play Space invaders. It is my first discord bot... so please give any suggestions to improve it :] Commands

2 Dec 30, 2021
A simple script & container to pull COVID data from covidlive.com.au and post a summary to a slack channel

CovidLive AU Summary Slackbot This bot is a very simple slackbot that pulls data, summarises and posts up to date AU COVID stats to a provided slack c

James 3 Dec 18, 2021
Bezlik Year Calendar Planner

Bezlik Year Calendar Planner Scribus script for creating year planners on one page A1 paper format. Script is based on Year-Calendar-Script-for-Scribu

Bohdan Bobrowski 2 May 24, 2022