Skip to content

QtInstrumentor

🛈 DocStrings

OpenTelemetry instrumentor for Qt / PrettyQt applications.

Automatically sends spans and metrics to whichever OpenTelemetry TracerProvider / MeterProvider is configured (including Logfire via logfire.configure(), Jaeger, Grafana Tempo, or InMemorySpanExporter).

Can be used via instrument() / uninstrument(), as a context manager (with QtInstrumentor(): ...), or via with app.trace_mode(): ....

Source code in prettyqt/telemetry/instrumentor.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
class QtInstrumentor:
    """OpenTelemetry instrumentor for Qt / PrettyQt applications.

    Automatically sends spans and metrics to whichever OpenTelemetry
    `TracerProvider` / `MeterProvider` is configured (including Logfire via
    `logfire.configure()`, Jaeger, Grafana Tempo, or `InMemorySpanExporter`).

    Can be used via `instrument()` / `uninstrument()`, as a context manager
    (`with QtInstrumentor(): ...`), or via `with app.trace_mode(): ...`.
    """

    def __init__(
        self,
        *,
        tracer_provider: Any = None,
        meter_provider: Any = None,
        trace_slots: bool = True,
        trace_emits: bool = False,
        trace_ui_events: bool = True,
        trace_timers: bool = True,
        trace_workers: bool = True,
        trace_network: bool = True,
        record_metrics: bool = False,
        ui_event_types: Collection[QtCore.QEvent.Type] | None = None,
        slot_filter: Callable[[signalhooks.SignalInfo, Callable[..., Any]], bool]
        | None = None,
    ) -> None:
        self._tracer_provider = tracer_provider
        self._meter_provider = meter_provider
        self._trace_slots = trace_slots
        self._trace_emits = trace_emits
        self._trace_ui_events = trace_ui_events
        self._trace_timers = trace_timers
        self._trace_workers = trace_workers
        self._trace_network = trace_network
        self._record_metrics = record_metrics
        self._ui_event_types: frozenset[QtCore.QEvent.Type] = (
            DEFAULT_UI_EVENT_TYPES
            if ui_event_types is None
            else frozenset(ui_event_types)
        )
        self._slot_filter = slot_filter

        self._instrumented = False
        self._signal_hook: TelemetrySignalHook | None = None
        self._prev_notify_hook: Any = None
        self._orig_single_shot: Any = None
        self._orig_start_callback_timer: Any = None
        self._orig_start_worker: Any = None
        self._orig_network_methods: dict[str, Any] = {}

    @property
    def is_instrumented(self) -> bool:
        return self._instrumented

    def instrument(self) -> Self:
        """Activate instrumentation hooks."""
        _otel.require_opentelemetry()
        if self._instrumented:
            return self
        if self._trace_slots or self._trace_emits:
            self._install_signal_hook()
        if self._trace_ui_events:
            self._install_notify_hook()
        if self._trace_timers:
            self._install_timer_hooks()
        if self._trace_workers:
            self._install_worker_hook()
        if self._trace_network:
            self._install_network_hooks()
        self._instrumented = True
        return self

    def uninstrument(self) -> None:
        """Deactivate and cleanly restore all patched Qt hooks."""
        if not self._instrumented:
            return
        self._uninstall_network_hooks()
        self._uninstall_worker_hook()
        self._uninstall_timer_hooks()
        self._uninstall_notify_hook()
        self._uninstall_signal_hook()
        self._instrumented = False

    def __enter__(self) -> Self:
        return self.instrument()

    def __exit__(self, *exc_info: object) -> None:
        self.uninstrument()

    # --- Signal / Slot hook ---

    def _install_signal_hook(self) -> None:
        hook = TelemetrySignalHook(
            tracer_provider=self._tracer_provider,
            meter_provider=self._meter_provider,
            trace_slots=self._trace_slots,
            trace_emits=self._trace_emits,
            record_metrics=self._record_metrics,
            slot_filter=self._slot_filter,
        )
        signalhooks.get_hook_manager().register(hook)
        self._signal_hook = hook

    def _uninstall_signal_hook(self) -> None:
        if self._signal_hook is not None:
            signalhooks.get_hook_manager().unregister(self._signal_hook)
            self._signal_hook = None

    # --- UI event notify hook ---

    def _install_notify_hook(self) -> None:
        from prettyqt.core.coreapplication import CoreApplicationMixin

        self._prev_notify_hook = CoreApplicationMixin._notify_hook
        CoreApplicationMixin._notify_hook = self._on_notify

    def _uninstall_notify_hook(self) -> None:
        from prettyqt.core.coreapplication import CoreApplicationMixin

        if CoreApplicationMixin._notify_hook == self._on_notify:
            CoreApplicationMixin._notify_hook = self._prev_notify_hook
        self._prev_notify_hook = None

    def _on_notify(
        self,
        receiver: Any,
        event: Any,
        call_next: Callable[[Any, Any], bool],
    ) -> bool:
        if event is None or event.type() not in self._ui_event_types:
            return call_next(receiver, event)
        ev_name = _event_type_name(event.type())
        attrs: dict[str, Any] = {
            "qt.event.type": ev_name,
            "qt.receiver.type": type(receiver).__name__,
        }
        with contextlib.suppress(RuntimeError, AttributeError):
            if obj_name := receiver.objectName():
                attrs["qt.receiver.name"] = obj_name
        tracer = _otel.get_tracer(self._tracer_provider)
        span_name = f"qt.event {ev_name}"
        with tracer.start_as_current_span(span_name, attributes=attrs) as span:
            try:
                return call_next(receiver, event)
            except BaseException as exc:
                _otel.record_span_exception(span, exc)
                raise

    # --- Timer context propagation hooks ---

    def _install_timer_hooks(self) -> None:
        orig_single_shot = QtCore.QTimer.singleShot

        @staticmethod
        def patched_single_shot(*args: Any, **kwargs: Any) -> Any:
            if (
                len(args) >= _MIN_SINGLE_SHOT_ARGS
                and callable(args[-1])
                and signalhooks.is_wrappable_slot(args[-1])
                and not _is_skipped_slot(args[-1])
            ):
                wrapped_cb = _otel.capture_context(args[-1])
                args = (*args[:-1], wrapped_cb)
            return orig_single_shot(*args, **kwargs)

        try:
            QtCore.QTimer.singleShot = patched_single_shot  # ty: ignore[invalid-assignment]
            self._orig_single_shot = orig_single_shot
        except TypeError:
            logger.debug("Binding does not allow patching QTimer.singleShot")

        from prettyqt.core.object import ObjectMixin

        orig_start_cb = ObjectMixin.start_callback_timer

        def patched_start_callback_timer(
            obj_self: Any,
            callback: Callable[..., Any],
            *args: Any,
            **kwargs: Any,
        ) -> Any:
            if callable(callback) and not _is_skipped_slot(callback):
                callback = _otel.capture_context(callback)
            return orig_start_cb(obj_self, callback, *args, **kwargs)

        ObjectMixin.start_callback_timer = patched_start_callback_timer  # ty: ignore[invalid-assignment]
        self._orig_start_callback_timer = orig_start_cb

    def _uninstall_timer_hooks(self) -> None:
        if self._orig_single_shot is not None:
            QtCore.QTimer.singleShot = self._orig_single_shot
            self._orig_single_shot = None
        if self._orig_start_callback_timer is not None:
            from prettyqt.core.object import ObjectMixin

            ObjectMixin.start_callback_timer = self._orig_start_callback_timer
            self._orig_start_callback_timer = None

    # --- ThreadPool worker context propagation & span ---

    def _install_worker_hook(self) -> None:
        from prettyqt.core.threadpool import ThreadPool, Worker

        orig_start_worker = ThreadPool.start_worker
        tracer_provider = self._tracer_provider

        def patched_start_worker(
            pool_self: Any,
            fn_or_worker: Callable[..., Any] | Worker,
            args: tuple[Any, ...] | None = None,
            kwargs: dict[str, Any] | None = None,
            priority: int = 0,
            result_fn: Callable[..., Any] | None = None,
            finished_fn: Callable[..., Any] | None = None,
            progress_fn: Callable[..., Any] | None = None,
            error_fn: Callable[..., Any] | None = None,
        ) -> Any:
            if callable(fn_or_worker):
                worker = Worker(
                    fn_or_worker,
                    *(args or ()),
                    **(kwargs or {}),
                )
            else:
                worker = fn_or_worker

            fn_name = signalhooks.get_callable_name(worker.fn)
            orig_fn = worker.fn
            captured = _otel.get_current_context()

            if inspect.isgeneratorfunction(orig_fn):

                def traced_gen(*w_args: Any, **w_kwargs: Any) -> Any:
                    token = _otel.attach_context(captured)
                    tracer = _otel.get_tracer(tracer_provider)
                    attrs = {
                        "qt.worker.name": fn_name,
                        "thread.name": threading.current_thread().name,
                    }
                    try:
                        with tracer.start_as_current_span(
                            f"qt.worker {fn_name}", attributes=attrs
                        ) as span:
                            try:
                                yield from orig_fn(*w_args, **w_kwargs)
                            except BaseException as exc:
                                _otel.record_span_exception(span, exc)
                                raise
                    finally:
                        _otel.detach_context(token)

                worker.fn = traced_gen
            else:

                def traced_fn(*w_args: Any, **w_kwargs: Any) -> Any:
                    token = _otel.attach_context(captured)
                    tracer = _otel.get_tracer(tracer_provider)
                    attrs = {
                        "qt.worker.name": fn_name,
                        "thread.name": threading.current_thread().name,
                    }
                    try:
                        with tracer.start_as_current_span(
                            f"qt.worker {fn_name}", attributes=attrs
                        ) as span:
                            try:
                                return orig_fn(*w_args, **w_kwargs)
                            except BaseException as exc:
                                _otel.record_span_exception(span, exc)
                                raise
                    finally:
                        _otel.detach_context(token)

                worker.fn = traced_fn

            if result_fn is not None:
                result_fn = _otel.capture_context(result_fn)
            if finished_fn is not None:
                finished_fn = _otel.capture_context(finished_fn)
            if progress_fn is not None:
                progress_fn = _otel.capture_context(progress_fn)
            if error_fn is not None:
                error_fn = _otel.capture_context(error_fn)

            return orig_start_worker(
                pool_self,
                worker,
                priority=priority,
                result_fn=result_fn,
                finished_fn=finished_fn,
                progress_fn=progress_fn,
                error_fn=error_fn,
            )

        ThreadPool.start_worker = patched_start_worker  # ty: ignore[invalid-assignment]
        self._orig_start_worker = orig_start_worker

    def _uninstall_worker_hook(self) -> None:
        if self._orig_start_worker is not None:
            from prettyqt.core.threadpool import ThreadPool

            ThreadPool.start_worker = self._orig_start_worker
            self._orig_start_worker = None

    # --- QNetworkAccessManager W3C traceparent injection & client spans ---

    def _install_network_hooks(self) -> None:
        try:
            from prettyqt.qt import QtNetwork
        except ImportError:
            return

        nam_cls = QtNetwork.QNetworkAccessManager
        tracer_provider = self._tracer_provider
        method_map = {
            "get": "GET",
            "head": "HEAD",
            "post": "POST",
            "put": "PUT",
            "deleteResource": "DELETE",
        }

        for attr, http_method in method_map.items():
            orig_method = getattr(nam_cls, attr, None)
            if orig_method is None:
                continue

            def _make_wrapper(orig: Any, verb: str) -> Callable[..., Any]:
                def wrapped(
                    nam_self: Any,
                    request: Any,
                    *rest: Any,
                    **kwargs: Any,
                ) -> Any:
                    if not isinstance(request, QtNetwork.QNetworkRequest):
                        return orig(nam_self, request, *rest, **kwargs)
                    tracer = _otel.get_tracer(tracer_provider)
                    url_str = request.url().toString()
                    span = tracer.start_span(
                        f"HTTP {verb}",
                        kind=_otel.client_span_kind(),
                        attributes={
                            "http.request.method": verb,
                            "url.full": url_str,
                        },
                    )
                    ctx = _otel.set_span_in_context(span)
                    _otel.inject_trace_headers(request, context=ctx)
                    try:
                        reply = orig(nam_self, request, *rest, **kwargs)
                    except BaseException as exc:
                        _otel.record_span_exception(span, exc)
                        span.end()
                        raise

                    if reply is not None:
                        status_attr = (
                            QtNetwork.QNetworkRequest.Attribute.HttpStatusCodeAttribute
                        )
                        no_err = QtNetwork.QNetworkReply.NetworkError.NoError

                        def _on_finished() -> None:
                            try:
                                code = reply.attribute(status_attr)
                                if code is not None:
                                    span.set_attribute(
                                        "http.response.status_code", int(code)
                                    )
                                err = reply.error()
                                if err != no_err:
                                    _otel.set_span_error(span, reply.errorString())
                            finally:
                                span.end()

                        _on_finished._prettyqt_skip_trace = True  # ty: ignore[missing-attribute]
                        reply.finished.connect(_on_finished)
                    else:
                        span.end()
                    return reply

                return wrapped

            try:
                setattr(nam_cls, attr, _make_wrapper(orig_method, http_method))
                self._orig_network_methods[attr] = orig_method
            except TypeError:
                logger.debug(
                    "Binding does not allow patching QNetworkAccessManager.%s", attr
                )

    def _uninstall_network_hooks(self) -> None:
        if not self._orig_network_methods:
            return
        from prettyqt.qt import QtNetwork

        nam_cls = QtNetwork.QNetworkAccessManager
        for attr, orig_method in self._orig_network_methods.items():
            setattr(nam_cls, attr, orig_method)
        self._orig_network_methods.clear()

instrument() -> Self

Activate instrumentation hooks.

Source code in prettyqt/telemetry/instrumentor.py
def instrument(self) -> Self:
    """Activate instrumentation hooks."""
    _otel.require_opentelemetry()
    if self._instrumented:
        return self
    if self._trace_slots or self._trace_emits:
        self._install_signal_hook()
    if self._trace_ui_events:
        self._install_notify_hook()
    if self._trace_timers:
        self._install_timer_hooks()
    if self._trace_workers:
        self._install_worker_hook()
    if self._trace_network:
        self._install_network_hooks()
    self._instrumented = True
    return self

uninstrument() -> None

Deactivate and cleanly restore all patched Qt hooks.

Source code in prettyqt/telemetry/instrumentor.py
def uninstrument(self) -> None:
    """Deactivate and cleanly restore all patched Qt hooks."""
    if not self._instrumented:
        return
    self._uninstall_network_hooks()
    self._uninstall_worker_hook()
    self._uninstall_timer_hooks()
    self._uninstall_notify_hook()
    self._uninstall_signal_hook()
    self._instrumented = False

:fa-brands-github: Show source on GitHub