Skip to content

Spans issued in Google Cloud Functions are not tied to a single Trace ID #202

@kamillle

Description

@kamillle

Spans that are automatically issued when my application running on Cloud Functions receives HTTP requests and other spans that are created by explicitly entering span in my code are tied to different trace IDs, resulting in poor browsability.
Below is my code. I would appreciate help if anyone knows why they are tied to different Trace IDs or if anyone else has encountered the same phenomenon.
By the way, when I traced almost the same code to an application running in Cloud Run, all spans were tied to one Trace ID.

My code is below

This is main.py and handler method is deployed to Cloud Functions as entry point

### main.py
from tracing import init_trace, add_trace_span

init_trace(environment="production")

@add_trace_span
def handler(req: Request) -> Response:
    # do something

This is tracing.py

### tracing.py ###

from functools import lru_cache, wraps

from opentelemetry import trace
from opentelemetry.trace import Tracer
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.sampling import TraceIdRatioBased
from opentelemetry.sdk.resources import Resource
from opentelemetry.propagate import set_global_textmap
from opentelemetry.propagators.cloud_trace_propagator import (
    CloudTraceFormatPropagator,
)

def init_trace(environment: str):
    set_global_textmap(CloudTraceFormatPropagator())
    tracer_provider = TracerProvider(
        sampler=TraceIdRatioBased(1),
        resource=Resource.create(
            {
                "service.name": "sample-application",
                "service.environment": environment,
            }
        ),
    )
    exporter = CloudTraceSpanExporter(resource_regex="service.*")
    tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))
    trace.set_tracer_provider(tracer_provider)

def add_trace_span(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        tracer = get_tracer()
        with tracer.start_as_current_span(name=f.__qualname__):
            return f(*args, **kwargs)

    return wrapper

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions