Skip to main content

TraceId is a trace ID generator based on Python contextvars. It automatically passes the trace ID in asynchronous tasks, enabling cross-coroutine tracing.

Project description

TraceId

codecov

TraceId is a trace ID generator based on Python contextvars. It automatically passes the trace ID in asynchronous tasks, enabling cross-coroutine tracing.

Installation

Install via pip

pip install traceid

Install via poetry

poetry add traceid

Usage

Generate trace ID

from traceid import TraceId
TraceId.gen()

Set trace ID

from traceid import TraceId
TraceId.set('your trace id')

Get trace ID

from traceid import TraceId
TraceId.get()

Clear trace ID

from traceid import TraceId
TraceId.clear()

Check if trace ID has been set/generated

from traceid import TraceId
TraceId.is_set()

Integrate with Fastapi

import typing

from fastapi import FastAPI, Request, Response
from traceid import TraceId
from aiorow import Connection, DSN


app = FastAPI()

@app.middleware("http")
async def add_trace_id(
    request: Request, call_next: typing.Callable[[Request], typing.Awaitable[Response]]
) -> Response:
    trace_id = request.headers.get("X-Request-ID", None)
    if trace_id is None:
        TraceId.gen()
    else:
        TraceId.set(trace_id)
    response = await call_next(request)
    response.headers["X-Request-ID"] = str(TraceId.get())
    return response
@app.get("/")
def read_root():
    return {"Hello": "World"}

Integrate with logging

import logging
import logging.config
import os

from traceid import JSONFormatter


LOG_SETTINGS = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "level": logging.INFO,
            "formatter": "json",
        },
    },
    "formatters": {
        "json": {
            "()": JSONFormatter,
        },
    },
    "loggers": {
        "": {"level": logging.INFO, "handlers": ["console"], "propagate": True},
    },
}

logging.config.dictConfig(LOG_SETTINGS)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

traceid-1.1.1.tar.gz (4.7 kB view hashes)

Uploaded Source

Built Distribution

traceid-1.1.1-py3-none-any.whl (5.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page