add Trace_lwt optional library

provides a with_span that's lwt friendly, as well as a ambient span
provider.
This commit is contained in:
Simon Cruanes 2026-04-13 12:37:19 -04:00
parent 83d408355b
commit feb50a6b8e
3 changed files with 38 additions and 1 deletions

View file

@ -22,13 +22,14 @@
(synopsis
"A lightweight stub for tracing/observability, agnostic in how data is collected")
(description
"ocaml-trace can be used to instrument libraries and programs with low overhead.\n\n It doesn't do any IO unless a collector is plugged in, which only\n the final executable should do.")
"ocaml-trace can be used to instrument libraries and programs with low overhead. It doesn't do any IO unless a collector is plugged in, which only the final executable should do.")
(depends
(ocaml
(>= 4.08))
dune)
(depopts
unix
lwt
(thread-local-storage (>= 0.2))
(mtime
(>= 2.0)))

6
src/lwt/dune Normal file
View file

@ -0,0 +1,6 @@
(library
(name trace_lwt)
(public_name trace.lwt)
(optional) ; lwt
(libraries trace.core lwt)
(synopsis "Interface with lwt"))

30
src/lwt/trace_lwt.ml Normal file
View file

@ -0,0 +1,30 @@
(** Optional interface with lwt.
@since NEXT_RELEASE *)
open Trace_core
let k_ambient_span : span Lwt.key = Lwt.new_key ()
let ambient_span_provider : Trace_core.Ambient_span_provider.t =
ASP_some
( (),
{
get_current_span = (fun () -> Lwt.get k_ambient_span);
with_current_span_set_to =
(fun () span f ->
Lwt.with_value k_ambient_span (Some span) (fun () -> f span));
} )
let with_span ?level ?__FUNCTION__ ~__FILE__ ~__LINE__ ?parent ?params ?data
name (f : span -> 'a Lwt.t) : 'a Lwt.t =
if Trace_core.enabled () then (
let span =
Trace_core.enter_span ?level ?__FUNCTION__ ~__FILE__ ~__LINE__ ?parent
?params ?data name
in
let fut = Trace_core.with_current_span_set_to span f in
Lwt.on_termination fut (fun () -> Trace_core.exit_span span);
fut
) else
f Trace_core.Collector.dummy_span