mirror of
https://github.com/ocaml-tracing/ocaml-opentelemetry.git
synced 2026-03-12 05:26:17 -04:00
feat(cohttp): read trace context from traceparent header
This commit is contained in:
parent
a1115661b4
commit
c9dbab94f9
1 changed files with 13 additions and 12 deletions
|
|
@ -1,3 +1,5 @@
|
||||||
|
module Otel = Opentelemetry
|
||||||
|
module Otel_lwt = Opentelemetry_lwt
|
||||||
open Cohttp
|
open Cohttp
|
||||||
open Cohttp_lwt
|
open Cohttp_lwt
|
||||||
|
|
||||||
|
|
@ -29,21 +31,20 @@ let span_attrs (req : Request.t) =
|
||||||
[ ("http.request.header.referer", `String r) ] )
|
[ ("http.request.header.referer", `String r) ] )
|
||||||
]
|
]
|
||||||
|
|
||||||
|
let trace_context_of_headers req =
|
||||||
|
let module Traceparent = Otel.Trace_context.Traceparent in
|
||||||
|
match Header.get (Request.headers req) Traceparent.name with
|
||||||
|
| None -> None, None
|
||||||
|
| Some v ->
|
||||||
|
(match Traceparent.of_value v with
|
||||||
|
| Ok (trace_id, parent_id) -> (Some trace_id, Some parent_id)
|
||||||
|
| Error _ -> None, None)
|
||||||
|
|
||||||
let trace ~service_name (callback : ('conn, 'body) callback ) : ('conn, 'body) callback =
|
let trace ~service_name (callback : ('conn, 'body) callback ) : ('conn, 'body) callback =
|
||||||
fun conn req body ->
|
fun conn req body ->
|
||||||
let trace_id =
|
let trace_id, parent_id = trace_context_of_headers req in
|
||||||
Header.get (Request.headers req) "trace-id"
|
|
||||||
|> Option.map (fun s ->
|
|
||||||
s |> Bytes.of_string |> Opentelemetry.Trace_id.of_bytes )
|
|
||||||
in
|
|
||||||
let parent_id =
|
|
||||||
Header.get (Request.headers req) "parent-id"
|
|
||||||
|> Option.map (fun s ->
|
|
||||||
s |> Bytes.of_string |> Opentelemetry.Span_id.of_bytes )
|
|
||||||
in
|
|
||||||
let open Lwt.Syntax in
|
let open Lwt.Syntax in
|
||||||
Opentelemetry_lwt.Trace.with_
|
Otel_lwt.Trace.with_
|
||||||
~service_name
|
~service_name
|
||||||
"request"
|
"request"
|
||||||
~kind:Span_kind_server
|
~kind:Span_kind_server
|
||||||
|
|
@ -52,7 +53,7 @@ let trace ~service_name (callback : ('conn, 'body) callback ) : ('conn, 'body) c
|
||||||
?trace_id
|
?trace_id
|
||||||
(fun scope ->
|
(fun scope ->
|
||||||
let* (res, body) = callback conn req body in
|
let* (res, body) = callback conn req body in
|
||||||
Opentelemetry.Trace.add_attrs scope (fun () ->
|
Otel.Trace.add_attrs scope (fun () ->
|
||||||
let code = Response.status res in
|
let code = Response.status res in
|
||||||
let code = Code.code_of_status code in
|
let code = Code.code_of_status code in
|
||||||
[ ("http.status_code", `Int code) ]) ;
|
[ ("http.status_code", `Int code) ]) ;
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue