OpenTelemetry Python API#

安装 OpenTelemetry#

[1]:
pip install opentelemetry-api opentelemetry-sdk
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: opentelemetry-api in /home/vmihailenco/.local/lib/python3.10/site-packages (1.14.0)
Requirement already satisfied: opentelemetry-sdk in /home/vmihailenco/.local/lib/python3.10/site-packages (1.14.0)
Requirement already satisfied: setuptools>=16.0 in /usr/lib/python3/dist-packages (from opentelemetry-api) (59.6.0)
Requirement already satisfied: deprecated>=1.2.6 in /home/vmihailenco/.local/lib/python3.10/site-packages (from opentelemetry-api) (1.2.13)
Requirement already satisfied: opentelemetry-semantic-conventions==0.35b0 in /home/vmihailenco/.local/lib/python3.10/site-packages (from opentelemetry-sdk) (0.35b0)
Requirement already satisfied: typing-extensions>=3.7.4 in /home/vmihailenco/.local/lib/python3.10/site-packages (from opentelemetry-sdk) (4.4.0)
Requirement already satisfied: wrapt<2,>=1.10 in /home/vmihailenco/.local/lib/python3.10/site-packages (from deprecated>=1.2.6->opentelemetry-api) (1.14.1)
Note: you may need to restart the kernel to use updated packages.

使用控制台导出器配置 OpenTelemetry#

[2]:
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter

trace.set_tracer_provider(TracerProvider())
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(ConsoleSpanExporter())
)

使用跟踪器创建跨度#

[3]:
import time

tracer = trace.get_tracer("app_or_package_name", "1.0.0")

# measure the timing of the operation
with tracer.start_as_current_span("operation-name") as span:
    time.sleep(1)
{
    "name": "operation-name",
    "context": {
        "trace_id": "0xff14cec5f33afeca0d04ced2c2185b39",
        "span_id": "0xd06e73b03bd55b4a",
        "trace_state": "[]"
    },
    "kind": "SpanKind.INTERNAL",
    "parent_id": null,
    "start_time": "2022-12-07T13:46:11.050878Z",
    "end_time": "2022-12-07T13:46:12.051944Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {},
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.14.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}

记录属性#

[4]:
with tracer.start_as_current_span("operation-name") as span:
    if span.is_recording():
        span.set_attribute("enduser.id", "jupyter")
        span.set_attribute("enduser.email", "jupyter@redis-py")
    time.sleep(1)
{
    "name": "operation-name",
    "context": {
        "trace_id": "0xfc11f0cc7afeefd79134eea639f5c78b",
        "span_id": "0xee791bf3cab65079",
        "trace_state": "[]"
    },
    "kind": "SpanKind.INTERNAL",
    "parent_id": null,
    "start_time": "2022-12-07T13:46:30.886188Z",
    "end_time": "2022-12-07T13:46:31.887323Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {
        "enduser.id": "jupyter",
        "enduser.email": "jupyter@redis-py"
    },
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.14.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}

更改跨度类型#

[5]:
with tracer.start_as_current_span("operation-name", kind=trace.SpanKind.SERVER) as span:
    time.sleep(0.1)
{
    "name": "operation-name",
    "context": {
        "trace_id": "0x2b4d1ba36423e6c17067079f044b5b62",
        "span_id": "0x323d6107cfe594bd",
        "trace_state": "[]"
    },
    "kind": "SpanKind.SERVER",
    "parent_id": null,
    "start_time": "2022-12-07T13:53:20.538393Z",
    "end_time": "2022-12-07T13:53:20.638595Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {},
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.14.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}

异常会自动记录#

[6]:
with tracer.start_as_current_span("operation-name", kind=trace.SpanKind.SERVER) as span:
    time.sleep(0.1)
    raise ValueError
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[6], line 3
      1 with tracer.start_as_current_span("operation-name", kind=trace.SpanKind.SERVER) as span:
      2     time.sleep(0.1)
----> 3     raise ValueError

ValueError:
{
    "name": "operation-name",
    "context": {
        "trace_id": "0x20457d98d4456b99810163027c7899de",
        "span_id": "0xf16e4c1620091c72",
        "trace_state": "[]"
    },
    "kind": "SpanKind.SERVER",
    "parent_id": null,
    "start_time": "2022-12-07T13:55:24.108227Z",
    "end_time": "2022-12-07T13:55:24.208771Z",
    "status": {
        "status_code": "ERROR",
        "description": "ValueError: "
    },
    "attributes": {},
    "events": [
        {
            "name": "exception",
            "timestamp": "2022-12-07T13:55:24.208730Z",
            "attributes": {
                "exception.type": "ValueError",
                "exception.message": "",
                "exception.stacktrace": "Traceback (most recent call last):\n  File \"/home/vmihailenco/.local/lib/python3.10/site-packages/opentelemetry/trace/__init__.py\", line 573, in use_span\n    yield span\n  File \"/home/vmihailenco/.local/lib/python3.10/site-packages/opentelemetry/sdk/trace/__init__.py\", line 1033, in start_as_current_span\n    yield span_context\n  File \"/tmp/ipykernel_241440/2787006841.py\", line 3, in <module>\n    raise ValueError\nValueError\n",
                "exception.escaped": "False"
            }
        }
    ],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.14.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}

使用嵌套块创建子跨度#

[7]:
with tracer.start_as_current_span("operation-name") as span:
    time.sleep(0.1)
    with tracer.start_as_current_span("child-span") as span:
        span.set_attribute("foo", "bar")
{
    "name": "child-span",
    "context": {
        "trace_id": "0x5625fbd0a1be15b49cda0d2bb236d158",
        "span_id": "0xc13b2c102566ffaf",
        "trace_state": "[]"
    },
    "kind": "SpanKind.INTERNAL",
    "parent_id": "0xa5f1a9afdf26173c",
    "start_time": "2022-12-07T13:57:14.011221Z",
    "end_time": "2022-12-07T13:57:14.011279Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {
        "foo": "bar"
    },
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.14.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}
{
    "name": "operation-name",
    "context": {
        "trace_id": "0x5625fbd0a1be15b49cda0d2bb236d158",
        "span_id": "0xa5f1a9afdf26173c",
        "trace_state": "[]"
    },
    "kind": "SpanKind.INTERNAL",
    "parent_id": null,
    "start_time": "2022-12-07T13:57:13.910849Z",
    "end_time": "2022-12-07T13:57:14.011320Z",
    "status": {
        "status_code": "UNSET"
    },
    "attributes": {},
    "events": [],
    "links": [],
    "resource": {
        "attributes": {
            "telemetry.sdk.language": "python",
            "telemetry.sdk.name": "opentelemetry",
            "telemetry.sdk.version": "1.14.0",
            "service.name": "unknown_service"
        },
        "schema_url": ""
    }
}