API reference¶
Generated reference documentation for each package. The pages are rebuilt and published with this
site from main.
| Language | Reference | Generated by |
|---|---|---|
| TypeScript | TypeScript API | TypeDoc |
| Rust | Rust API · docs.rs | rustdoc |
| Go | pkg.go.dev | Go doc comments |
| Python | below | mkdocstrings |
| Java | Java API | Javadoc |
Build them locally with make docs (per language: make -C <lang> docs).
Python¶
Grow Codes SDK for Apache SkyWalking.
from grow_apache_skywalking import SkyWalkingClient, SkyWalkingConfig client = SkyWalkingClient.from_env() # doctest: +SKIP
AttrValue
module-attribute
¶
Attribute value: scalar, list of values or nested mapping (OTel AnyValue without bytes).
AsyncBaseLogQueryClient ¶
Async :class:BaseLogQueryClient.
AsyncBaseTraceQueryClient ¶
Async :class:BaseTraceQueryClient.
query_trace_id ¶
The id wait_for_trace passes to get_trace; override to keep native ids.
AsyncBatchProcessor ¶
Bases: _BatchCore
Batches records for an :class:AsyncLogExporter on an asyncio task.
The task starts on the running loop at the first :meth:add (or :meth:flush). :meth:add
may be called from other threads; it wakes the worker thread-safely. Exports are bounded by
export_timeout_s with :func:asyncio.wait_for.
add ¶
Queue without blocking; False when dropped (block acts as drop_newest here).
add_wait
async
¶
Queue a record, waiting for queue space with drop_policy="block".
flush
async
¶
Export everything queued now; raises TimeoutError when timeout_s passes first.
shutdown
async
¶
Drain (bounded by timeout_s), stop the task, shut the exporter down; idempotent.
AsyncBatchingLogClient ¶
Bases: _ClientBase
:class:AsyncLogClient over an :class:AsyncLogExporter + :class:AsyncBatchProcessor.
AsyncHttpTransport ¶
Asynchronous transport (one per async client); options as for :class:HttpTransport.
Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError
subclass) so asyncio's cancellation machinery keeps working. Every call after
:meth:aclose raises :class:CancelledError ("client is closed").
AsyncLogClient ¶
Bases: Protocol
Asynchronous log client: send stays synchronous, flush/close are awaited.
AsyncLogExporter ¶
Bases: Protocol
Asynchronous exporter, awaited by :class:AsyncBatchProcessor on the caller's event loop.
AsyncLogQueryClient ¶
Bases: Protocol
Asynchronous query API (same methods, awaited).
AsyncPollingTail ¶
Async :class:PollingTail; the polling task runs on the current event loop.
AsyncSkyWalkingClient ¶
Asynchronous Apache SkyWalking OAP client; use async with or call :meth:aclose.
Same modules and methods as :class:SkyWalkingClient, awaited. Cancel a call by
cancelling its task: the SDK raises :class:CancelledError, which is also an
:class:asyncio.CancelledError.
aclose
async
¶
Flush and close owned log clients and tracing handles, then release connections. Idempotent.
from_env
classmethod
¶
Build a client from the environment (see :class:SkyWalkingConfig).
graphql
async
¶
Raw GraphQL (same as client.query.graphql).
init_tracing ¶
:func:init_tracing with this client's config. :meth:aclose shuts it down.
log_client ¶
log_client(*, service_name: str | None = None, service_instance: str | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True) -> AsyncBatchingLogClient
An :class:AsyncBatchingLogClient sending native logs over this client's
connections. :meth:aclose flushes and closes it.
AsyncSkyWalkingLogExporter ¶
Asynchronous :class:SkyWalkingLogExporter (:class:AsyncLogExporter).
AsyncSkyWalkingLogQueryClient ¶
Bases: AsyncBaseLogQueryClient
Asynchronous :class:SkyWalkingLogQueryClient. Obtain it from
AsyncSkyWalkingClient.logs.
search
async
¶
search(query: str, *, start: datetime | None = None, end: datetime | None = None, limit: int = 100, order: SearchOrder = 'desc', cursor: str | None = None) -> LogSearchResult
See :meth:SkyWalkingLogQueryClient.search.
AsyncSkyWalkingQueryClient ¶
Asynchronous :class:SkyWalkingQueryClient (same methods, awaited). Obtain it from
AsyncSkyWalkingClient.query; cancel a call by cancelling its task.
capabilities
async
¶
See :meth:SkyWalkingQueryClient.capabilities.
find_service
async
¶
See :meth:SkyWalkingQueryClient.find_service.
get_trace
async
¶
See :meth:SkyWalkingQueryClient.get_trace.
graphql
async
¶
See :meth:SkyWalkingQueryClient.graphql.
list_endpoints
async
¶
list_endpoints(service: str, keyword: str | None = None, *, limit: int = 100) -> list[SkyWalkingEndpoint]
See :meth:SkyWalkingQueryClient.list_endpoints.
list_instances
async
¶
See :meth:SkyWalkingQueryClient.list_instances.
list_log_tag_keys
async
¶
See :meth:SkyWalkingQueryClient.list_log_tag_keys.
list_services
async
¶
See :meth:SkyWalkingQueryClient.list_services.
query_logs
async
¶
query_logs(*, service: str | None = None, instance: str | None = None, endpoint: str | None = None, trace_id: str | None = None, segment_id: str | None = None, span_id: int | None = None, keywords: Sequence[str] = (), excluding_keywords: Sequence[str] = (), tags: Mapping[str, str] | None = None, range: TimeRange | None = None, paging: Paging | None = None, order: LogOrder = 'DES') -> QueryLogsResult
See :meth:SkyWalkingQueryClient.query_logs.
query_traces
async
¶
query_traces(*, service: str | None = None, instance: str | None = None, endpoint: str | None = None, trace_id: str | None = None, trace_state: TraceState = 'ALL', min_duration_ms: float | None = None, max_duration_ms: float | None = None, tags: Mapping[str, str] | None = None, range: TimeRange | None = None, paging: Paging | None = None, order: TraceOrder = 'BY_START_TIME') -> QueryTracesResult
See :meth:SkyWalkingQueryClient.query_traces.
topology
async
¶
topology(range: TimeRange | None = None, *, service: str | None = None, layer: str | None = None) -> Topology
See :meth:SkyWalkingQueryClient.topology.
AsyncSkyWalkingTraceQueryClient ¶
Bases: AsyncBaseTraceQueryClient
Asynchronous :class:SkyWalkingTraceQueryClient (same methods, awaited). Obtain it from
AsyncSkyWalkingClient.traces.
get_dependencies
async
¶
get_dependencies(*, start: datetime | None = None, end: datetime | None = None) -> list[DependencyLink]
See :meth:SkyWalkingTraceQueryClient.get_dependencies.
get_trace
async
¶
See :meth:SkyWalkingTraceQueryClient.get_trace.
list_operations
async
¶
See :meth:SkyWalkingTraceQueryClient.list_operations.
list_services
async
¶
See :meth:SkyWalkingTraceQueryClient.list_services.
search_traces
async
¶
See :meth:SkyWalkingTraceQueryClient.search_traces.
wait_for_trace
async
¶
wait_for_trace(trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1) -> Trace
See :meth:SkyWalkingTraceQueryClient.wait_for_trace.
AsyncTraceQueryClient ¶
Bases: Protocol
Asynchronous trace query API (same methods, awaited).
AuthenticationError ¶
Bases: SkyWalkingError
Credentials missing or rejected (HTTP 401).
BaseConfig
dataclass
¶
Common, immutable client settings. Durations are float seconds (timedelta accepted).
Service configs subclass this (@dataclass(frozen=True, repr=False)), override url
with the service default, add their own fields (Secret for credentials), extend
:meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.
BaseLogQueryClient ¶
Base for service query clients: implement :meth:search, override what the service has.
tail defaults to :class:PollingTail; list_streams/list_labels raise
UnsupportedError; wait_for_log uses :func:wait_for_log.
BaseTraceQueryClient ¶
Base for service query clients; every method raises UnsupportedError until overridden
(wait_for_trace uses :func:wait_for_trace on top of get_trace, passing the id
through :meth:query_trace_id).
query_trace_id ¶
The id wait_for_trace passes to get_trace; override to keep native ids.
BatchOptions
dataclass
¶
Batching options; durations are float seconds (timedelta accepted).
max_export_retries/retry_backoff_s: a batch whose export failed with a retryable
SDK error (raised, or returned with nothing accepted) is exported again up to
max_export_retries times, waiting retry_backoff_s * 2**n before retry n.
Partial acceptance is final.
from_mapping
classmethod
¶
Build from the camelCase form used by conformance scenarios (flushIntervalMs …).
BatchProcessor ¶
Bases: _BatchCore
Batches records for a synchronous :class:LogExporter on a daemon worker thread.
The worker starts with the first record. It exports when a batch is full, when
flush_interval_s passed since the first queued record, on :meth:flush and on
:meth:shutdown. Processors with a started worker are shut down at interpreter exit.
add ¶
Queue a record; False when it was dropped. Blocks only with drop_policy="block".
flush ¶
Export everything queued now; raises TimeoutError when timeout_s passes first.
shutdown ¶
Drain the queue (bounded by timeout_s), stop the worker and shut the exporter down.
Idempotent. Records still queued when the timeout passes are dropped with reason
shutdown; later :meth:add calls are dropped the same way.
BatchStats
dataclass
¶
Counters of a batch processor (see the module docs for their meaning).
BatchingLogClient ¶
Bases: _ClientBase
:class:LogClient over a synchronous :class:LogExporter and a :class:BatchProcessor.
redaction defaults to RedactionProcessor(); pass None to disable it.
correlate adds the active span's ids to records without a trace id.
CancelToken ¶
Thread-safe cancellation flag passed to sync calls as cancel=.
Cancelling interrupts an in-flight request (the call returns immediately with
:class:CancelledError; the abandoned HTTP exchange finishes in the background) and any
retry backoff sleep.
CancelledError ¶
Bases: SkyWalkingError, CancelledError
The caller cancelled the operation (task cancel, :class:CancelToken, client close).
Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.
ConfigError ¶
Bases: SkyWalkingError
Invalid or missing configuration.
ConflictError ¶
Bases: SkyWalkingError
Conflict or failed precondition (HTTP 409, 412, CAS mismatch).
EnvReader ¶
Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.
Every getter returns None when no variable is set (empty strings count as unset). A
present but invalid value raises :class:ConfigError that names the variable, never its
value.
ErrorCode ¶
Bases: str, Enum
Canonical error codes; the value is the wire form used by the conformance suite.
ErrorInfo
dataclass
¶
Passed to Hooks.on_error; error is the (redacted) SDK error.
ExportResult
dataclass
¶
Outcome of one :meth:LogExporter.export call.
retries is a Python extension: the number of transport retries the export needed
(summed into BatchStats.retries).
GraphQLDuration
dataclass
¶
The GraphQL Duration input (times in the OAP timezone, formatted per step).
GraphQLErrorInfo
dataclass
¶
One entry of a GraphQL errors array.
GraphQLResponse
dataclass
¶
Result of a raw GraphQL call: partial data is possible next to errors.
HealthStatus
dataclass
¶
Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.
Hooks
dataclass
¶
Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.
HttpTransport ¶
Synchronous transport (one per client).
Service options (all optional):
request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default("retry-after",), e.g.("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.error_mapper:mapper(error, response)returns a service-specific error for an HTTP error response (orNoneto keep the default). The mapped error is whatHooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.
Every call after :meth:close raises :class:CancelledError ("client is closed").
InstanceAttribute
dataclass
¶
A {name, value} attribute of a service instance.
KeyValue
dataclass
¶
A {key, value} pair (span tags, log tags, log data).
LogClient ¶
Bases: Protocol
Synchronous log client (SPEC LogClient).
LogExporter ¶
Bases: Protocol
Synchronous exporter, called from the :class:BatchProcessor worker thread.
export sends one batch and reports how many records the service accepted. It may raise
an SDK error instead of returning ExportResult(error=...); both count as failed records.
timeout_s is the per-batch export budget the exporter should pass to its transport.
LogHandler ¶
Bases: Handler
:class:logging.Handler that forwards records to a log client.
Attributes: extra= fields, logger.name, code.filepath/code.function/
code.lineno, thread.name and exception.* for exc_info. Records from loggers
in exclude_loggers (prefix match; defaults to the HTTP stack the exporters use) and from
the SDK's own worker threads are skipped to avoid feedback loops. When a formatter is set,
the formatted text is the body; otherwise record.getMessage().
LogInput
dataclass
¶
Convenience input for :meth:LogClient.send; defaults are filled by the client.
LogQueryClient ¶
Bases: Protocol
Synchronous query API. Services without a query API raise UnsupportedError.
LogRecord
dataclass
¶
One log record (OTel log data model subset). Treat instances as immutable.
from_json
classmethod
¶
Parse the normalized wire form; raises ValidationError for malformed input.
to_json ¶
Normalized wire form (spec/schemas/log-record.schema.json, camelCase keys).
severity is the OTel number; timestamps are RFC 3339 UTC with microseconds.
to_json_str ¶
Compact JSON text of :meth:to_json (UTF-8 safe, non-JSON values via str).
LogSearchResult
dataclass
¶
One page of search results.
LogSink ¶
Bases: Protocol
Anything that accepts records: every log client.
Logger ¶
Small structured logger writing to a :class:LogSink.
Records below min_severity are discarded. The sink fills timestamp, resource and trace
correlation (the active OpenTelemetry span) for records without a trace id.
child ¶
Logger with the same sink and level and the extra attributes.
LoggerLike ¶
Bases: Protocol
Structured logger interface accepted in configuration (SPEC Logger).
NativeIdSpan
dataclass
¶
NativeIdSpanLink
dataclass
¶
NativeIdTrace
dataclass
¶
NativeLog
dataclass
¶
A log entry as stored by OAP (timestamp in epoch milliseconds).
NativeSpan
dataclass
¶
A span as stored by SkyWalking (agents, /v3/segments); identity = (segment_id,
span_id). Times are epoch milliseconds; parent_span_id -1 = segment root.
NativeSpanLog
dataclass
¶
A log entry recorded on a native span (time in epoch milliseconds).
NativeSpanRef
dataclass
¶
Cross-segment reference of a native span.
NativeTrace
dataclass
¶
A native trace: the spans of every segment.
NotFoundError ¶
Bases: SkyWalkingError
Missing record (HTTP 404).
Paging
dataclass
¶
1-based page selection (page_size 1..10000).
ParsedLogQuery
dataclass
¶
Parsed form of a log search query (see :func:parse_log_query).
PermissionDeniedError ¶
Bases: SkyWalkingError
Authenticated but not allowed (HTTP 403).
PollingTail ¶
tail built on search: a daemon thread polls for records newer than the last one.
Errors go to on_error (default: ignored) and polling continues. :meth:stop is idempotent.
QueryLogsResult
dataclass
¶
Result of query_logs.
QueryTracesResult
dataclass
¶
Result of query_traces: whole traces (every segment) that match.
RateLimitError ¶
Bases: SkyWalkingError
Too many requests (HTTP 429); retry_after holds the requested delay when known.
RedactionProcessor ¶
Returns redacted copies of records.
Attribute names containing one of keys (case-insensitive substring) get replacement
as value, recursively through nested mappings and lists. patterns (regular expressions or
their source strings) are replaced in the body and in every string attribute value.
:class:Secret values are always replaced.
Request
dataclass
¶
One logical API call (possibly several attempts).
path is joined to the base URL ({name} style values must already be encoded; use
:func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for
pagination links the service returns; the default headers, config.headers included,
are sent there too, so only pass URLs of the same service). json is encoded when not
None; content sends raw bytes. idempotent overrides the method rule; an
idempotency_key sends the Idempotency-Key header and marks the request idempotent.
raise_for_status=False returns error responses instead of raising (retries still
apply). Statuses in allow_status are expected answers (a 404 that carries data, a
health endpoint's 503): the response is returned at once, like a success, without retries
or on_error.
RequestInfo
dataclass
¶
Passed to Hooks.on_request; url and headers are redacted.
ResolvedRange
dataclass
¶
A window in epoch milliseconds.
ResourceRegistry ¶
Holds :class:Stoppable objects; :meth:stop_all stops each once, ignoring errors.
register ¶
Track item; when the registry is already closed the item is stopped now.
Response
dataclass
¶
A completed HTTP response (body fully read).
ResponseInfo
dataclass
¶
Passed to Hooks.on_response; headers are the redacted response headers (rate
limit headers and the like stay readable).
RetryPolicy
dataclass
¶
Retry settings. Durations are seconds (datetime.timedelta is accepted).
Backoff for retry n (0-based) is full jitter:
random(0, min(max_backoff, initial_backoff * multiplier ** n)).
random returns a float in [0, 1); inject it in tests for deterministic sleeps.
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
Severity ¶
Bases: IntEnum
Log severity; the values are the OpenTelemetry severity numbers.
SkyWalkingCapabilities
dataclass
¶
Server features probed once per client.
SkyWalkingClient ¶
Synchronous Apache SkyWalking OAP client. Thread-safe; use as a context manager or call
:meth:close.
Modules: :attr:query (GraphQL query API), :attr:traces (SPEC TraceQueryClient),
:attr:logs (SPEC LogQueryClient); :meth:log_client and :meth:init_tracing create
log clients and tracing handles that :meth:close flushes and shuts down. Every I/O method
accepts cancel= (a :class:CancelToken) to abort from another thread.
http_transport (an httpx transport, e.g. httpx.MockTransport) and now
(epoch-ms clock) are test seams; max_scan_pages bounds the raw pages one log search may
scan (default 10).
query
property
¶
The GraphQL query API: services, endpoints, instances, native traces, logs, topology.
traces
property
¶
SPEC TraceQueryClient (Zipkin store for OTLP spans, native store for agents).
close ¶
Flush and close log clients and tracing handles created here, stop background resources and release connections. Idempotent.
from_env
classmethod
¶
Build a client from the GROW_APACHE_SKYWALKING_* and vendor environment
variables (see :class:SkyWalkingConfig).
graphql ¶
graphql(query: str, variables: Mapping[str, Any] | None = None, *, cancel: CancelToken | None = None) -> GraphQLResponse
Raw GraphQL (same as client.query.graphql).
health ¶
Liveness: GET /healthcheck (OAP health checker, SW_HEALTH_CHECKER=default):
200 → ok, 503 → unhealthy. Without the health checker (404) falls back to GraphQL
checkHealth (score 0 = ok). Never raises for an unhealthy or unreachable service
(only :class:CancelledError and :class:ConfigError).
init_tracing ¶
:func:init_tracing with this client's config (OTLP endpoint, protocol, token).
:meth:close shuts the handle down.
log_client ¶
log_client(*, service_name: str | None = None, service_instance: str | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True) -> BatchingLogClient
A :class:BatchingLogClient sending native logs (POST /v3/logs) over this
client's connections. :meth:close flushes and closes it.
ping ¶
Timed GraphQL round trip (getTimeInfo; also caches the OAP timezone); returns
milliseconds. OAP has no query authentication: :class:AuthenticationError only comes
from a gateway in front of it.
request ¶
Send a raw request to the OAP REST port (retries, hooks, redaction).
server_version ¶
OAP version from GraphQL {version} (e.g. 10.4.0-b272da3).
SkyWalkingConfig
dataclass
¶
Bases: BaseConfig
Immutable settings for :class:~grow_apache_skywalking.SkyWalkingClient.
Common fields (url, timeouts, retry, tls, proxy, headers,
user_agent_suffix, hooks, logger) come from :class:BaseConfig. Durations are
float seconds; datetime.timedelta is accepted.
Service fields:
url- OAP REST/GraphQL base (port 12800), defaulthttp://127.0.0.1:12800; a trailing/graphqlis stripped.graphql_path- GraphQL path belowurl(default/graphql).otlp_endpoint- OTLP endpoint for :func:init_tracing(defaulthttp://<url host>:11800, the OAP gRPC receiver).otlp_protocol-grpc(default; OAP 10.4 has no OTLP/HTTP receiver) orhttp/protobuf(only for an OpenTelemetry Collector in front of OAP).otlp_headers- extra OTLP exporter headers (gRPC metadata), keys lower-cased.zipkin_url- Zipkin v2 query API base (defaulthttp://<url host>:9412/zipkin).authentication- OAP gRPC token (SW_AUTHENTICATION), a :class:Secret, sent as theauthenticationmetadata on OTLP exports. OAP does not protect GraphQL or/v3/*with it.trace_backend- trace store read byclient.traces:zipkin(OTLP spans),native(SkyWalking agent segments) orauto(default).
Environment (:meth:from_env): explicit keyword > GROW_APACHE_SKYWALKING_<NAME> >
vendor variables (:data:VENDOR_ENV, in order) > default. Names: URL,
GRAPHQL_PATH, OTLP_ENDPOINT, OTLP_PROTOCOL, OTLP_HEADERS,
AUTHENTICATION, ZIPKIN_URL, TRACE_BACKEND plus the common CONNECT_TIMEOUT,
REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT,
CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY. SW_GRAPHQL_URL loses a trailing
/graphql, SW_AGENT_COLLECTOR_BACKEND_SERVICES (host:port) becomes
http://host:port and SW_ZIPKIN_ADDRESS gains /zipkin.
SkyWalkingEndpoint
dataclass
¶
An endpoint (operation) of a service.
SkyWalkingInstance
dataclass
¶
A service instance.
SkyWalkingLogExporter ¶
:class:LogExporter posting batches to OAP's native log API (POST /v3/logs, JSON
array, port 12800).
Native logs carry the trace context, register the service and are queryable a few seconds
later. The body is sent uncompressed (gzip is ignored: compression is not verified on
OAP's HTTP receiver). Transport errors are raised (the batch processor retries retryable
ones).
SkyWalkingLogQueryClient ¶
Bases: BaseLogQueryClient
:class:LogQueryClient for SkyWalking (GraphQL queryLogs).
OAP on BanyanDB ignores content keywords, so free-text terms are filtered client side:
search reads raw pages of 1000 logs (newest first by default) and keeps the matching
ones until limit matches or max_scan_pages pages; next_cursor
("page:offset:size") continues where it stopped. Without free text the page size is
limit and only the exact time window is filtered. Default window: the last hour. See
:func:parse_log_query for the syntax. Obtain it from SkyWalkingClient.logs.
list_labels ¶
Log tag keys seen in the last hour (queryLogTagAutocompleteKeys).
list_streams ¶
Service names known to OAP (SkyWalking has no streams; the service is the equivalent).
search ¶
search(query: str, *, start: datetime | None = None, end: datetime | None = None, limit: int = 100, order: SearchOrder = 'desc', cursor: str | None = None, cancel: CancelToken | None = None) -> LogSearchResult
Search logs (see the class description for the query syntax and paging).
SkyWalkingQueryClient ¶
The SkyWalking GraphQL query API (POST /graphql on port 12800), synchronous.
Obtain it from SkyWalkingClient.query. Every method accepts cancel= (a
:class:CancelToken).
capabilities ¶
Server features (hasQueryTracesV2Support, supportQueryLogsByKeywords), cached.
find_service ¶
One service by name: findService; None when unknown.
get_trace ¶
One native trace: queryTrace(traceId); None when unknown (OTLP trace ids are
never native).
graphql ¶
graphql(query: str, variables: Mapping[str, Any] | None = None, *, cancel: CancelToken | None = None) -> GraphQLResponse
Raw GraphQL: returns data and errors (partial data possible). HTTP 400
(syntax/validation errors) raises :class:ValidationError.
list_endpoints ¶
list_endpoints(service: str, keyword: str | None = None, *, limit: int = 100, cancel: CancelToken | None = None) -> list[SkyWalkingEndpoint]
Endpoints of a service: findEndpoint(keyword, serviceId, limit). keyword is a
tokenised match (downstream finds /native/downstream, down does not). No
duration is sent (OAP 10.4 + BanyanDB returns nothing with one).
list_instances ¶
list_instances(service: str, range: TimeRange | None = None, *, cancel: CancelToken | None = None) -> list[SkyWalkingInstance]
Instances of a service active in range (default last hour): listInstances.
list_log_tag_keys ¶
list_log_tag_keys(range: TimeRange | None = None, *, cancel: CancelToken | None = None) -> list[str]
Log tag keys seen in range (default last hour): queryLogTagAutocompleteKeys.
list_services ¶
list_services(layer: str | None = None, range: TimeRange | None = None, *, cancel: CancelToken | None = None) -> list[SkyWalkingService]
Services: listServices(layer). layer None = all layers; an unknown layer
→ []. OAP has no time filter for services: range is accepted for API symmetry
and ignored. Services that only sent OTLP traces are not listed (use
client.traces.list_services()).
query_logs ¶
query_logs(*, service: str | None = None, instance: str | None = None, endpoint: str | None = None, trace_id: str | None = None, segment_id: str | None = None, span_id: int | None = None, keywords: Sequence[str] = (), excluding_keywords: Sequence[str] = (), tags: Mapping[str, str] | None = None, range: TimeRange | None = None, paging: Paging | None = None, order: LogOrder = 'DES', cancel: CancelToken | None = None) -> QueryLogsResult
Logs: queryLogs(condition). Either a window (default last hour) or trace_id
(relatedTrace) is sent. keywords/excluding_keywords go to the server when it
supports keyword search (Elasticsearch storage); on BanyanDB the returned page is
filtered client side (case-insensitive substring). tags must be keys in
SW_SEARCHABLE_LOGS_TAG_KEYS.
query_traces ¶
query_traces(*, service: str | None = None, instance: str | None = None, endpoint: str | None = None, trace_id: str | None = None, trace_state: TraceState = 'ALL', min_duration_ms: float | None = None, max_duration_ms: float | None = None, tags: Mapping[str, str] | None = None, range: TimeRange | None = None, paging: Paging | None = None, order: TraceOrder = 'BY_START_TIME', cancel: CancelToken | None = None) -> QueryTracesResult
Native traces: queryTraces(condition) (whole traces). instance/endpoint
need service; durations in ms; tags must be keys in the server's
SW_SEARCHABLE_TAG_KEYS. The window (default last hour) is omitted when only
trace_id is given. The legacy queryBasicTraces is not used (unsupported on
BanyanDB).
time_info ¶
OAP clock and timezone: getTimeInfo.
topology ¶
topology(range: TimeRange | None = None, *, service: str | None = None, layer: str | None = None, cancel: CancelToken | None = None) -> Topology
Service topology in range (default last hour): getGlobalTopology(duration,
layer), or getServiceTopology when service is set. Native traffic only (OTLP
spans create no edges); includes the virtual User node.
SkyWalkingService
dataclass
¶
A service known to OAP (native agents, native logs, OTLP logs).
SkyWalkingTraceQueryClient ¶
Bases: BaseTraceQueryClient
:class:TraceQueryClient for SkyWalking (see the module description for the backends).
Obtain it from SkyWalkingClient.traces. Every method accepts cancel=.
get_dependencies ¶
get_dependencies(*, start: datetime | None = None, end: datetime | None = None, cancel: CancelToken | None = None) -> list[DependencyLink]
Service dependencies from the native topology (call_count is 0: the topology
carries no counts; default window last hour). OAP 10.4 does not implement Zipkin
/dependencies, so the zipkin backend raises :class:UnsupportedError; OTLP
spans create no topology edges.
get_trace ¶
One trace in the SPEC model, None when it does not exist. Zipkin rejects non-hex
ids with :class:ValidationError.
list_operations ¶
Operation names of a service (Zipkin span names and/or native endpoint names).
list_services ¶
Service names (sorted, unique). New services appear about 30-35 s after their first data (OAP flushes its name index periodically).
search_traces ¶
search_traces(query: TraceSearchQuery | None = None, *, cancel: CancelToken | None = None) -> list[TraceSummary]
SPEC search.
Zipkin: service → serviceName, operation → spanName (lower-cased like
OAP stores names), tags → annotationQuery (k=v and …; keys must be in
SW_ZIPKIN_SEARCHABLE_TAG_KEYS), durations in µs, endTs = end (default now),
lookback = end - start. Native: queryTraces with operation as endpoint
name and durations in ms (default window: last hour).
wait_for_trace ¶
wait_for_trace(trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1) -> Trace
Poll :meth:get_trace until the trace has min_spans spans (TimeoutError
otherwise). Native ids are used verbatim; hex ids are normalized.
Span
dataclass
¶
A finished span as returned by a query API.
Ids are normalized on construction (an all-zero or empty parent_span_id becomes
None); a negative duration_micros (the default) is computed from start and end.
A subclass with normalize_ids = False keeps native ids verbatim (an empty
parent_span_id still becomes None); link_class is used by :meth:from_json.
SpanBatchOptions
dataclass
¶
BatchSpanProcessor settings; durations are float seconds (timedelta accepted).
SpanLink
dataclass
¶
A link to another span. Set normalize_ids = False on a subclass for native ids.
SpanNode
dataclass
¶
A span with its children (sorted like :func:sort_spans).
SpanStatus
dataclass
¶
from_json
classmethod
¶
Parse {"code", "message"?} (a bare code string is accepted too).
Sw8Context
dataclass
¶
Decoded sw8 header (SkyWalking cross-process propagation v3).
Sw8InjectContext
dataclass
¶
Sw8Propagator ¶
Bases: TextMapPropagator
OpenTelemetry propagator for SkyWalking headers (propagator name sw8).
- extract (default use): a valid
sw8header is stored in the context (:func:get_sw8_context, :func:sw8_attributes); its trace id is not hex, so the W3C context stays the OpenTelemetry trace.sw8-correlationentries are added to the baggage. - inject: only when native metadata was set with :func:
with_sw8_context; otherwise nothing is written (an OpenTelemetry span has no segment id or native span id).
extract ¶
extract(carrier: CarrierT, context: Context | None = None, getter: Getter[CarrierT] = default_getter) -> Context
Read sw8 into the context and sw8-correlation into the baggage.
inject ¶
inject(carrier: CarrierT, context: Context | None = None, setter: Setter[CarrierT] = default_setter) -> None
Write sw8/sw8-correlation when the context carries :func:with_sw8_context
metadata.
TimeInfo
dataclass
¶
OAP clock: getTimeInfo.
TimeRange
dataclass
¶
Time window of a metadata/trace/log query.
Defaults: end = now, start = end - 1 h, step = MINUTE. Naive datetimes
are UTC.
TimeoutError ¶
Bases: SkyWalkingError
A connect, request or total deadline was exceeded (also HTTP 408, 504).
TlsConfig
dataclass
¶
TLS settings. insecure_skip_verify is for tests only and logs a warning once.
Topology
dataclass
¶
getGlobalTopology / getServiceTopology result.
TopologyCall
dataclass
¶
An edge of the service topology (source/target are node ids).
TopologyNode
dataclass
¶
A node of the service topology.
Trace
dataclass
¶
All spans of one trace, sorted by start time then span id.
A subclass with normalize_ids = False keeps a native trace id verbatim; span_class
is used by :meth:from_json.
TraceQueryClient ¶
Bases: Protocol
Synchronous trace query API.
TraceSearchQuery
dataclass
¶
matches ¶
Client-side filter: a span must match service/operation/tags; duration and time bounds apply to the whole trace.
TraceSummary
dataclass
¶
TracingASGIMiddleware ¶
ASGI middleware: one SERVER span per HTTP request, parent taken from request headers.
Non-HTTP scopes (lifespan, websocket) and excluded_paths pass through untraced.
TracingConfig
dataclass
¶
Settings for :func:init_tracing_with. repr redacts credential headers.
protocol and endpoint are interpreted by the service's exporter factory; the
template default protocol is http/protobuf. propagators beyond tracecontext,
baggage, b3 and b3multi need a factory from the service package.
protocol and propagators remember whether the caller set them: left out (or passed
as None) they read as :data:DEFAULT_TRACE_PROTOCOL / :data:DEFAULT_TRACE_PROPAGATORS
exactly as before, and :attr:protocol_set / :attr:propagators_set are False so a
service default can apply instead. The marker travels with the value, so
:meth:with_changes, dataclasses.replace and TracingConfig(**fields) keep an unset
field unset; passing the default value explicitly counts as set.
TracingHandle ¶
TracingWSGIMiddleware ¶
WSGI middleware: one SERVER span per request; ends when the response is closed.
UnavailableError ¶
Bases: SkyWalkingError
Network error or server unavailable (HTTP 500, 502, 503).
UnsupportedError ¶
Bases: SkyWalkingError
The service or deployment does not offer this capability (HTTP 501, missing API).
ValidationError ¶
Bases: SkyWalkingError
Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).
add_event ¶
Add an event to the active span (no-op without one).
annotation_to_event ¶
Decode an OAP annotation into an event.
name|{"k":"v"}|0 (split on the first and last |) → name + attributes; any other
value is the event name without attributes.
apoll_until
async
¶
apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = time.monotonic) -> T
Async :func:poll_until; fn is an async callable.
async_httpx_event_hooks ¶
async_httpx_event_hooks(*, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> dict[str, list[Callable[..., Any]]]
event_hooks for httpx.AsyncClient (same behaviour as :func:httpx_event_hooks).
async_wait_for_log
async
¶
async_wait_for_log(client: AsyncLogQueryClient, query: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, predicate: RecordPredicate | None = None) -> LogRecord
Async form of :func:wait_for_log.
async_wait_for_trace
async
¶
async_wait_for_trace(client: AsyncTraceQueryClient, trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1, normalize: Callable[[str], str] | None = normalize_trace_id) -> Trace
Async form of :func:wait_for_trace.
base_from_graphql_url ¶
Strip a trailing /graphql (with or without slash) from a GraphQL URL.
build_propagator ¶
build_propagator(names: Sequence[str], factories: Mapping[str, PropagatorFactory] | None = None) -> TextMapPropagator
Composite propagator for names; factories adds or overrides propagators by name.
build_resource ¶
Resource with service.name/service.version/deployment.environment and extras.
The environment is written both as deployment.environment.name (current semantic
conventions) and as the older deployment.environment. Merged on top of the SDK default
resource (telemetry.sdk.*, OTEL_RESOURCE_ATTRIBUTES); explicit config values win.
build_sampler ¶
OpenTelemetry sampler for a TracingConfig.sampler name.
build_tree ¶
Parent/child forest; spans whose parent is missing become roots.
collector_to_url ¶
host:port[,host:port] (SkyWalking agent collector address) → http://host:port.
create_async_log_client ¶
create_async_log_client(config: SkyWalkingConfig | None = None, *, service_name: str | None = None, service_instance: str | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True, http_transport: AsyncBaseTransport | None = None) -> AsyncBatchingLogClient
Asynchronous :func:create_log_client (an :class:AsyncBatchingLogClient).
create_log_client ¶
create_log_client(config: SkyWalkingConfig | None = None, *, service_name: str | None = None, service_instance: str | None = None, options: BatchOptions | None = None, resource: Mapping[str, AttrValue] | None = None, redaction: RedactionProcessor | None = _DEFAULT_REDACTION, correlate: bool = True, http_transport: BaseTransport | None = None) -> BatchingLogClient
Standalone :class:BatchingLogClient that sends native logs to POST /v3/logs.
It owns its connections; close() flushes and releases them. service_name /
service_instance become the service.name / service.instance.id resource
attributes (records without service.name go to unknown_service). config
defaults to :meth:SkyWalkingConfig.from_env.
current_span ¶
The active span (a non-recording invalid span when none is active).
current_span_id ¶
16-char lower-hex span id of the active span, or None.
current_trace_context ¶
(trace_id, span_id, trace_flags) of the active OpenTelemetry span, if any.
current_trace_id ¶
32-char lower-hex trace id of the active span, or None.
datetime_to_micros ¶
Microseconds since the epoch (naive datetimes are UTC).
decode_native_log ¶
Decode one native log from a GraphQL response.
decode_native_span ¶
Decode one native span from a GraphQL response (missing fields get neutral defaults).
decode_sw8 ¶
Decode an sw8 value; None when malformed (wrong field count, bad Base64 …).
decode_sw8_correlation ¶
Decode sw8-correlation; malformed entries are skipped.
default_tracer ¶
Tracer of this package from the global provider.
dependencies_from_spans ¶
Service dependency links (parent service → child service, different services only).
encode_sw8 ¶
Encode an sw8 value: sample-b64(traceId)-b64(segment)-spanId-b64(service)-
b64(instance)-b64(endpoint)-b64(peer).
encode_sw8_correlation ¶
Encode sw8-correlation: b64(key):b64(value),… in insertion order.
endpoint_id ¶
Endpoint id: service_id + "_" + base64(endpoint).
error_for_code ¶
Return the error class for a code (ErrorCode member or wire value).
error_from_status ¶
error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError
Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.
request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.
extract ¶
extract(carrier: Mapping[str, str], *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> otel_context.Context
Read a context from carrier (exact key match; use :func:extract_headers for HTTP).
extract_headers ¶
extract_headers(headers: HeaderSource, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> otel_context.Context
Read a context from HTTP headers (case-insensitive; mapping or ASGI-style byte pairs).
format_duration_time ¶
Format a time (datetime or epoch ms) for a Duration field.
DAY yyyy-MM-dd, HOUR yyyy-MM-dd HH, MINUTE yyyy-MM-dd HHmm,
SECOND yyyy-MM-dd HHmmss, in the OAP timezone given by offset_minutes.
format_timestamp ¶
RFC 3339 UTC form with microseconds and Z; naive datetimes are taken as UTC.
get_logger ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
get_sw8_context ¶
The sw8 context extracted from an incoming request, if any.
graphql_error ¶
graphql_error(operation: str, errors: tuple[GraphQLErrorInfo, ...] | list[GraphQLErrorInfo], known_secrets: list[str] | None = None) -> ServiceError
Map GraphQL errors to an SDK error.
UnsupportedOperationException → :class:UnsupportedError; anything else →
:class:ValidationError (bad input caught by the resolver). The message is redacted and
truncated to 300 characters.
graphql_errors ¶
Decode the errors array of a GraphQL response body.
httpx_event_hooks ¶
httpx_event_hooks(*, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> dict[str, list[Callable[..., Any]]]
event_hooks for httpx.Client: a CLIENT span per request with injected headers.
A request that fails before a response arrives (connection error) never reaches the
response hook, so its span is not exported; use :func:instrument_requests_session style
wrapping or with_span around the call when such failures must be traced.
init_tracing ¶
init_tracing(config: TracingConfig | None = None, *, skywalking: SkyWalkingConfig | None = None, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, **overrides: Any) -> TracingHandle
Set up OpenTelemetry tracing that exports OTLP/gRPC to SkyWalking OAP (SPEC §5).
Pass a :class:TracingConfig and/or its fields as keywords (service_name="checkout").
Endpoint, protocol, headers and token come from skywalking (default
:meth:SkyWalkingConfig.from_env): a TracingConfig field overrides them when it is set
(endpoint/tls not None, protocol different from the template default
http/protobuf) and keyword overrides always win; headers are merged. The sw8
propagator name is available (extract by default; see :class:Sw8Propagator). Spans are
readable with client.traces (Zipkin query API) about 5-15 s after export.
Raises :class:ConfigError for invalid settings.
init_tracing_with ¶
init_tracing_with(config: TracingConfig, exporter_factory: ExporterFactory, *, propagator_factories: Mapping[str, PropagatorFactory] | None = None, span_processors: Sequence[SpanProcessor] = (), id_generator: IdGenerator | None = None, sampler: Sampler | None = None) -> TracingHandle
Build a TracerProvider for config with a BatchSpanProcessor around the exporter.
Services wrap this in their init_tracing(config). propagator_factories lets a
service add datadog/sw8 style propagators; span_processors (extra processors,
e.g. a second exporter) are added after the batch processor; sampler replaces the one
built from config.sampler/sampler_ratio (remote or vendor samplers). With
config.set_global the provider and propagator become the
OpenTelemetry globals (the API allows one global provider per process: is_global on
the handle tells whether it took effect).
inject ¶
inject(carrier: MutableMapping[str, str] | None = None, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> MutableMapping[str, str]
Write the current (or given) context into carrier and return it.
Uses propagator or the global propagator (set by init_tracing_with).
inject_headers ¶
inject_headers(headers: MutableMapping[str, str] | None = None, *, context: Context | None = None, propagator: TextMapPropagator | None = None) -> MutableMapping[str, str]
Add propagation headers (traceparent, baggage …) to headers and return them.
instance_id ¶
Service instance id: service_id + "_" + base64(instance).
instrument_requests_session ¶
instrument_requests_session(session: Session, *, tracer: Tracer | None = None, propagator: TextMapPropagator | None = None) -> requests.Session
Trace every request sent through session (CLIENT span, headers injected).
Wraps session.send once; calling it again on the same session is a no-op.
is_bookkeeping_tag ¶
Tags OAP adds as bookkeeping (otel.*, error, w3c.tracestate).
is_hex_trace_id ¶
True for a 16- or 32-character hex id (OTLP/Zipkin), false for native SkyWalking ids.
key_values ¶
Decode a [{key, value}] list (non-string values as JSON, null → "").
log_to_record ¶
Map a stored log back to a SPEC :class:LogRecord.
Tag level → severity/severity_text (default INFO), span_id → span_id (16 hex), a
32-hex trace_id → trace_id (native trace ids go to attribute sw.trace_id), other
tags → attributes (strings), service/instance → resource service.name /
service.instance.id, endpoint → resource sw.endpoint.
mark_span_error ¶
Set ERROR status on span and record the exception (when error is one).
matches_text ¶
True when every term occurs (case-insensitive) in the content or a tag value.
micros_to_datetime ¶
Exact UTC datetime for microseconds since the epoch.
native_span_key ¶
Composite SPEC span id of a native span: <segmentId>-<spanId>.
native_span_to_span ¶
Convert a native span into the SPEC §5 model.
- Ids are kept verbatim:
span_id = "<segmentId>-<spanId>". - Parent: the same segment's
parent_span_idwhen >= 0, elserefs[0]("<parentSegmentId>-<parentSpanId>"); further refs become links. kind: Entry -> server, Exit -> client, Local -> internal.- Times: milliseconds -> microseconds. Status
errorwhenis_error. - Attributes: tags plus
sw.component,sw.layer,sw.peerandsw.service_instance(when set). - Span logs become events (name = the
eventdata value, elselog).
native_trace_from_spans ¶
Decode a list of native spans into a :class:NativeTrace; None when empty.
native_trace_to_trace ¶
Convert a native trace into a SPEC trace (spans sorted); None when empty.
normalize_headers ¶
Lower-cased header names → values; accepts mappings and (name, value) pairs incl. bytes.
normalize_span_id ¶
16-char lower-hex span id (left-padded); raises ValidationError when invalid.
normalize_trace_id ¶
32-char lower-hex trace id; 64-bit ids (16 hex chars, ints, 8 bytes) are left-padded.
Raises ValidationError for non-hex, too long or all-zero ids.
otlp_traces_url ¶
<endpoint>/v1/traces unless the endpoint already names that path.
parse_bool ¶
Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
Parse a duration into seconds.
Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s",
"2m", "1h", "1m30s"). Raises :class:ValueError for anything else.
parse_log_query ¶
Parse the log query syntax.
Space-separated key=value terms (service=, instance=, endpoint=,
trace_id=/traceId= map to the GraphQL condition; any other key is a server tag
filter and must be in SW_SEARCHABLE_LOGS_TAG_KEYS) plus free-text terms ("quoted
phrases" allowed). Every free-text term must occur (case-insensitive) in the content or in
a tag value.
parse_otlp_headers ¶
Parse OTEL-style headers k1=v1,k2=v2 (keys lower-cased, values percent-decoded).
Raises :class:ConfigError naming source (never the value) for a malformed entry.
parse_retry_after ¶
Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.
parse_timestamp ¶
Parse RFC 3339 (any fraction precision, Z/offset; none = UTC) to aware UTC.
parse_timezone ¶
OAP timezone (+0000, -0530, +08:00) → minutes east of UTC; unknown → 0.
poll_until ¶
poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T
Call fn every interval_s until it returns a ready value; return that value.
A value is ready when it is not None and predicate(value) is true (without a
predicate: not an empty container). Retryable SDK errors raised by fn are remembered
and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.
record_exception ¶
Record error as an exception event on the active span (status unchanged).
record_to_log_data ¶
record_to_log_data(record: LogRecord, default_service: str = DEFAULT_LOG_SERVICE_NAME) -> dict[str, Any]
Map a SPEC :class:LogRecord to native LogData (protobuf JSON mapping).
resource["service.name"] → service, service.instance.id → serviceInstance,
body → body.text.text, severity_text → tag level, attributes (stringified,
nested values as JSON) → tags, trace_id → traceContext.traceId (enables
relatedTrace queries), span_id → tag span_id.
redact_fields ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
Redact user info and every query value (all values, not only sensitive ones).
Query names are kept so the URL stays useful in logs.
resolve_range ¶
Apply the :class:TimeRange defaults and validate (ValidationError on bad input).
retry_after_from_headers ¶
retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None
Server requested delay in seconds from the first of names that parses.
Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset,
RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds;
timestamps are turned into the remaining delay.
service_id ¶
SkyWalking service id: base64(name) + ".1" (".0" for a virtual service).
set_error ¶
Mark the active span as failed: ERROR status, plus an exception event for exceptions.
skywalking_exporter_factory ¶
The span exporter for a resolved config (the exporter factory of
:func:init_tracing_with).
grpc → OTLP/gRPC to the OAP receiver (headers become gRPC metadata; https
endpoints use the TLS settings); http/protobuf → OTLP/HTTP protobuf to
<endpoint>/v1/traces (only for an OpenTelemetry Collector in front of OAP - OAP 10.4
serves no OTLP/HTTP). native raises :class:ConfigError: use the official SkyWalking
agents.
skywalking_tracing_defaults ¶
Service defaults for :class:TracingConfig: protocol/endpoint from
otlp_protocol/otlp_endpoint, headers from otlp_headers plus the
authentication token, tls from the client TLS settings.
sort_spans ¶
Spans sorted by start time, then span id.
span_from_readable ¶
Convert a finished OpenTelemetry SDK span (e.g. from an in-memory exporter).
span_kind ¶
SpanKind from an enum member or a name ("server"); None → INTERNAL.
structlog_processor ¶
Return a structlog processor that sends every event to client.
The event dict passes through unchanged, so put this processor before the renderer.
event becomes the body, level (or the method name) the severity, timestamp
(TimeStamper output, epoch float or datetime) the timestamp; exc_info and a rendered
exception become exception.* attributes; every other key is an attribute.
summarize ¶
Summary of a SPEC trace; the root falls back to the earliest span.
sw8_attributes ¶
Span attributes describing an extracted sw8 parent (sw8.parent.*,
sw8.peer).
tag_text ¶
An attribute value in SkyWalking's string tag form (JSON for lists and mappings).
to_attr_value ¶
Convert any Python value to an attribute value (unknown types become str(value)).
to_graphql_duration ¶
The GraphQL Duration of a resolved window.
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
topology_to_dependencies ¶
Topology → dependency links (parent = source node name, child = target node
name, call_count = 0: the topology type carries no call counts). Sorted.
trace_fields ¶
{"trace_id": …, "span_id": …} of the active span for log fields; {} without one.
traced ¶
traced(name_or_fn: str | Callable[P, R] | None = None, /, *, attributes: Attributes = None, kind: SpanKindLike = None, tracer: Tracer | None = None) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]
Decorator that runs a function (sync or async def) inside a span.
@traced, @traced() and @traced("name") all work; the default span name is the
function's qualified name. Async generators are not supported (the span would end before
iteration).
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.
wait_for_log ¶
wait_for_log(client: LogQueryClient, query: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, predicate: RecordPredicate | None = None) -> LogRecord
Poll client.search(query) until a record (matching predicate) shows up.
wait_for_trace ¶
wait_for_trace(client: TraceQueryClient, trace_id: str, *, timeout_s: float | timedelta = 30.0, interval_s: float | timedelta = 1.0, min_spans: int = 1, normalize: Callable[[str], str] | None = normalize_trace_id) -> Trace
Poll get_trace until the trace has min_spans spans; TimeoutError otherwise.
NotFoundError and retryable errors count as "not there yet". normalize turns
trace_id into the id passed to get_trace (default: 32-char lower hex); None
passes native ids verbatim.
with_span ¶
with_span(name: str, fn: Callable[[Span], R] | None = None, *, attributes: Attributes = None, kind: SpanKindLike = None, links: Sequence[Link | SpanContext] | None = None, tracer: Tracer | None = None) -> R | AbstractContextManager[otel_trace.Span]
Run fn(span) inside a new current span, or return a context manager without fn.
The span always ends. An exception is recorded, sets ERROR status and is re-raised
(cancellation, asyncio.CancelledError or the SDK CancelledError, is not). The
context-manager form also works inside async code (context is kept in contextvars).
with_sw8_context ¶
A context whose outgoing requests carry this native metadata as sw8 (and
sw8-correlation).
The SDK cannot derive native metadata from an OpenTelemetry span; supply it only when you bridge to SkyWalking agents.
zipkin_query_url ¶
A Zipkin address with or without the /zipkin path → <address>/zipkin.
zipkin_span_to_span ¶
Convert a stored Zipkin span into the SPEC §5 model.
Ids lower-case (trace id padded to 32), kind lower-case (absent → internal),
service_name = localEndpoint.serviceName, status from otel.status_code
(STATUS_CODE_ERROR → error with otel.status_description, STATUS_CODE_OK → ok; an
error tag alone → error), attributes = tags without the bookkeeping keys (values are
strings: OAP stores tags as text), annotations → events. Span names are lower-cased by OAP
on ingest.
zipkin_spans_from_body ¶
The well-formed spans (objects with string traceId and id) of a response body.
zipkin_trace_id ¶
Lower-case and validate a Zipkin trace id; :class:ValidationError otherwise.
zipkin_trace_to_trace ¶
Convert one Zipkin trace into a SPEC :class:Trace; None when empty.
zipkin_traces_from_body ¶
The non-empty traces of a [[span…]…] body.