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
Collaboration with Microsoft, AWS, Google, and ETHZürich Analytics Club (2022 Datathon Project)

DATATHON_ Collaboration with Microsoft, AWS, Google, and ETHZürich Analytics Club (2022 Datathon Project) Datathon Original Challenge SAV DataDays Rei

esthi 34 Nov 10, 2022
A Python Client for News API

newsapi-python A Python client for the News API. License Provided under MIT License by Matt Lisivick. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRAN

Matt Lisivick 281 Dec 29, 2022
Posts word definitions on Twitter daily

Word Of The Day bot Post daily word definitions on social media. Twitter account: https://twitter.com/WordOfTheDay_B Introduction The goal of this pro

Lucas Rijllart 1 Jan 08, 2022
Discord opsiyonel detaylı hava durumu botu

WeatherBot Discord opsiyonel detaylı hava durumu botu önümüzdeki Perşembe ──► önümüzdeki Çarşamba ┌─────────┐┌─────────┐┌─────────┐┌───────

DejaVu 16 Dec 19, 2022
You cant check for conflicts until course enrolment actually opens. I wanted to do it earlier.

AcornICS I noticed that Acorn it does not let you check if a timetable is valid based on the enrollment cart, it also does not let you visualize it ea

Isidor Kaplan 2 Sep 16, 2021
BSDotPy, A module to get a bombsquad player's account data.

BSDotPy BSDotPy, A module to get a bombsquad player's account data from bombsquad's servers. Badges Provided By: shields.io Acknowledgements Issues Pu

Rudransh Joshi 3 Feb 17, 2022
Boto is a Python package that provides interfaces to Amazon Web Services.

Boto is a Python package that provides interfaces to Amazon Web Services.

the boto project 6.5k Jan 01, 2023
ApiMoedas - This API is a extesion of API

🪙 Api Moeda 🪙 Este projeto é uma extensão da API Awesome API. Basicamente, ele mostra todas as moedas que a Awesome API tem e todas as suas conversõ

Abel 4 May 29, 2022
Discord.py(disnake) selfbot

Zzee selfbot Discord.py selfbot Version: 1.0 ATTENTION! we are not responsible for your discord account! this program violates the ToS discord rules!

1 Jan 10, 2022
An advanced telegram country information finder bot.

Country-Info-Bot-V2 An advanced telegram country information finder bot Made with Python3 (C) @FayasNoushad Copyright permission under MIT License Lic

Fayas Noushad 16 Nov 12, 2022
A Python wrapper for the WooCommerce API.

WooCommerce API - Python Client A Python wrapper for the WooCommerce REST API. Easily interact with the WooCommerce REST API using this library. Insta

WooCommerce 171 Dec 25, 2022
Discord-RAID-Tool - Hacks/tools

How to use Python must be installed run install-config If you dont have python installed, download python 3.7.6 and make sure you click on the 'ADD TO

1 Jan 01, 2022
Rio Userbot Adalah Bot Untuk Membantu Mempermudahkan Sesuatu Di Telegram, Last Repository With Pytgcalls v0.8.3

RIO - USERBOT Disclaimer Saya tidak bertanggung jawab atas penyalahgunaan bot ini. Bot ini dimaksudkan untuk bersenang-senang sekaligus membantu Anda

RioProjectX 4 Oct 18, 2022
Basic Python3 request wrapper for the PancakeSwap API

🐍 Python Pancakes 🥞 A simple request wrapper for the Pancake-Swap API. Installation Install package # Using pip $ pip install pythonpancakes # Or f

Scott Burlovich 30 Nov 20, 2022
Bot Realm of the Mad God Exalt (ROTMG). (Auto_nexus, Auto_HP, Auto_Loot)

Bot_ROTMG Bot Realm of the Mad God Exalt (ROTMG). (Auto_nexus, Auto_HP, Auto_Loot) *Este projeto visa apenas o aprendizado, quem faz mal uso é o único

Guilherme Silva Uchoa 1 Oct 30, 2021
A PowerFull Telegram Mirror Bot.......

- [ DEAD REPO AND NO MORE UPDATE ] Slam Mirror Bot Slam Mirror Bot is a multipurpose Telegram Bot written in Python for mirroring files on the Interne

αвιנтн 2 Nov 09, 2021
Requests based multi-threaded script for increasing followers on Spotify

Proxyless Spotify Follow Bot Requests based multi-threaded script for increasing followers on Spotify. Click here to report bugs. Usage Download ZIP h

397 Jan 03, 2023
Code for paper "Adversarial score matching and improved sampling for image generation"

Adversarial score matching and improved sampling for image generation This repo contains the official implementation for the ICLR 2021 paper Adversari

Alexia Jolicoeur-Martineau 114 Dec 11, 2022
A ideia é fornecer uma base ampla de questões do ENEM como uma api REST

base10 "A ideia é fornecer uma base ampla de questões do ENEM como uma api REST" TODO Documentar a api com apifairy Criar testes Criar crawler para si

Wadson Garbes 4 Apr 24, 2022