Skip to main content

GraftCode App Insights Connector (Python)

Configures Application Insights for an application, together with the Graft bridge spans, in one call. It is a port of the .NET (GraftCode.Netcore.Telemetry.AppInsightsConnector) and Java (com.graftcode.telemetry.appinsights) connectors.

from graftcode_telemetry_appinsights import GraftCodeAppInsightsConnector

with GraftCodeAppInsightsConnector.start("MyService") as telemetry:
    span = telemetry.start_span("MyOperation")
    telemetry.logger.info("My operation started {Step}", "one")
    span.end()

The connector reads APPLICATIONINSIGHTS_CONNECTION_STRING and exports traces and logs with the Azure Monitor exporter (azure-monitor-opentelemetry-exporter). It also attaches graftcode-instrumentation, so Hypertube calls produce Graftcode spans and Hypertube log lines go to the same pipeline. You can configure an explicit connection string with a callback or an options object:

from graftcode_telemetry_appinsights import GraftCodeAppInsightsConnector, GraftCodeAppInsightsConnectorOptions

def configure(options):
    options.service_name = "MyService"
    options.connection_string = settings["ApplicationInsights:ConnectionString"]

telemetry = GraftCodeAppInsightsConnector.start(configure)
telemetry = GraftCodeAppInsightsConnector.start(GraftCodeAppInsightsConnectorOptions(service_name="MyService"))
Option Default
service_name required; becomes service.name (the App Insights cloud role) and the tracer/logger name
connection_string falls back to APPLICATIONINSIGHTS_CONNECTION_STRING
minimum_log_level LogsLevel.Info; applies to the connector logger and to forwarded Hypertube lines
traces_per_second None (every trace is kept)
enable_console_logging True

Pipeline (GraftCodeAppInsightsConnectorPipeline)

Member Purpose
tracer, start_span(name, kind=INTERNAL, context=None) spans for the application
logger GraftCodeAppInsightsLogger (trace, debug, info, warning, error, log)
instrumentation the attached GraftcodeInstrumentation
force_flush(timeout_millis=5000) flushes traces and logs
close() / context manager flushes, detaches the instrumentation, and shuts the providers down; calling it twice is safe
is_exporting_to_app_insights() False when no connection string was resolved

The OpenTelemetry providers are not registered as globals, which matches the Java connector. Use pipeline.tracer or pipeline.start_span for application spans.

Logger

The logger uses the same message templates as the .NET and Java connectors:

  • {Name} placeholders are filled positionally. {{ and }} escape braces, and format specifiers ({Count:D3}) are ignored. None renders as (null).
  • Each placeholder becomes a log attribute. The raw template is stored as {OriginalFormat}.
  • Records are correlated with the current span.
  • Console output follows the .NET console layout:
info: TestGgPythonWebApi[0]
      Caller after Graft call Result=fetched

To log an exception, pass it first: logger.error(exception, "failed {Step}", "fetch"). It is attached as exception.type, exception.message and exception.stacktrace.

Hypertube's own lines reach App Insights through the standard-library logger Hypertube. The pipeline sets that logger's level from minimum_log_level and adds a handler that emits through the OpenTelemetry logs API (instrumentation scope Hypertube).

Request telemetry (ASGI)

Add the middleware to FastAPI or Starlette. It plays the role of UseGraftCodeAppInsightsConnectorRequestTelemetry in .NET and the servlet filter in Java:

app.add_middleware(GraftCodeAppInsightsRequestTelemetryMiddleware, telemetry=telemetry)

Each HTTP request gets a SERVER span that is current while the endpoint runs:

  • Parent: the incoming W3C traceparent, when present.
  • Attributes: http.method, http.target and http.status_code. A status of 500 or higher marks the span as failed, and exceptions are recorded and re-raised. The path goes in http.target rather than http.route (as .NET and Java use) because the Python Azure Monitor exporter replaces the request name with METHOD route whenever http.route or a full URL is present; with http.target the request keeps the controller-based name, as in .NET and Java.
  • Name: {ServiceName}.{controller} when the routed endpoint belongs to a class, for example a FetchController.fetch endpoint gives TestGgPythonWebApi.Fetch. An explicit name can be set in scope["state"]["graft.controller"]. Otherwise the name is {ServiceName} {METHOD} {path}.

Synchronous endpoints run in Starlette's thread pool with a copy of the context, so Graft calls made there share the request's trace.

Sampling

Every trace is kept by default (ALWAYS_ON); the reason is the same as in .NET and Java. Set traces_per_second to opt into a token-bucket RateLimitedSampler.

Flushing

The pipeline flushes on close(), at interpreter exit (atexit), and on unhandled exceptions; both sys.excepthook and threading.excepthook are chained. Short-lived processes should still call force_flush() before exiting.

Diagnosing missing telemetry

When no connection string is resolved, is_exporting_to_app_insights() returns False and telemetry stays local. The connector then logs Application Insights telemetry for {ServiceName} is disabled: no connection string was configured. ....

Tests

$env:PYTHONPATH = "<HYPERTUBE>\src\python;<graftcode-extensions>\observability\Instrumentation\python"
python -m pip install -e .[dev]
python -m pytest

Metadata

Release files for graftcode-telemetry-appinsights 1.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for graftcode-telemetry-appinsights 1.0.3
File Size Uploaded Provenance Actions
graftcode_telemetry_appinsights-1.0.3.tar.gz 16.2 kB Without provenance Details for graftcode_telemetry_appinsights-1.0.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for graftcode-telemetry-appinsights 1.0.3
File Interpreter ABI Platform Actions
graftcode_telemetry_appinsights-1.0.3-py3-none-any.whl Python 3 none any Details for graftcode_telemetry_appinsights-1.0.3-py3-none-any.whl

Total release size: 30.0 kB

Release files / graftcode_telemetry_appinsights-1.0.3.tar.gz

Download URL graftcode_telemetry_appinsights-1.0.3.tar.gz
Size 16.2 kB
Tags Source
SHA-256 checksum
How to use checksums
32e88c32cc30034bcb3569158590dee47c8d194cf2f3f3ccdaa18b105c439eb3
BLAKE2b-256 checksum
How to use checksums
d283098e3eab414b742401a3284f371337f06185e2f4c1dbeb742e2d8107fa9f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / graftcode_telemetry_appinsights-1.0.3-py3-none-any.whl

Download URL graftcode_telemetry_appinsights-1.0.3-py3-none-any.whl
Size 13.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2792f6ee3ac3f861781608c2052ff7d0eed7d068c1303dfead3065708e9a0626
BLAKE2b-256 checksum
How to use checksums
8753c6b125094aa1afe2ca609cdfaebe0933c9db30eddbaf248c433b3f279868
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for graftcode-telemetry-appinsights 1.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page