Module Message_templates.Metrics

Observability metrics for logging system

This module provides per-sink metrics collection including event counts, error tracking, and latency percentiles. Metrics are thread-safe and automatically tracked during logging operations.

Example:

  let metrics = Metrics.create () in

  (* Record event emission *)
  Metrics.record_event metrics ~sink_id:"file" ~latency_us:1.5;

  (* Get sink-specific metrics *)
  let file_metrics = Metrics.get_sink_metrics metrics "file" in
  Printf.printf "Events: %d, Dropped: %d, P95 latency: %.2fμs\n"
    file_metrics.events_total file_metrics.events_dropped
    file_metrics.latency_p95_us;

  (* Export all metrics as JSON *)
  let json = Metrics.to_json metrics in
  Yojson.Safe.pretty_to_channel stdout json
type sink_metrics = {
  1. sink_id : string;
    (*

    Sink identifier

    *)
  2. events_total : int;
    (*

    Total events emitted to this sink

    *)
  3. events_dropped : int;
    (*

    Events dropped due to queue overflow

    *)
  4. events_failed : int;
    (*

    Events that failed during emission

    *)
  5. bytes_written : int;
    (*

    Approximate bytes written to sink

    *)
  6. last_error : (exn * float) option;
    (*

    Most recent error (exception * timestamp) if any

    *)
  7. latency_p50_us : float;
    (*

    Median latency in microseconds

    *)
  8. latency_p95_us : float;
    (*

    95th percentile latency in microseconds

    *)
}

Per-sink metrics snapshot

type t

Metrics tracker (opaque)

val create : unit -> t

Create a new metrics tracker

  • returns

    A new empty metrics collection

val record_event : t -> sink_id:string -> latency_us:float -> unit

Record successful event emission

  • parameter t

    The metrics tracker

  • parameter sink_id

    Identifier for the sink

  • parameter latency_us

    Emission latency in microseconds

val record_drop : t -> sink_id:string -> unit

Record a dropped event

  • parameter t

    The metrics tracker

  • parameter sink_id

    Identifier for the sink

val record_error : t -> sink_id:string -> exn -> unit

Record an emission error

  • parameter t

    The metrics tracker

  • parameter sink_id

    Identifier for the sink

  • parameter exn

    The exception that occurred

val get_sink_metrics : t -> string -> sink_metrics option

Get metrics for a specific sink

  • parameter t

    The metrics tracker

  • parameter sink_id

    The sink identifier

  • returns

    Metrics snapshot if sink exists, None otherwise

val get_all_metrics : t -> sink_metrics list

Get metrics for all sinks

  • parameter t

    The metrics tracker

  • returns

    List of metrics for all active sinks

val reset : t -> unit

Reset all metrics

Clears all accumulated metrics.

  • parameter t

    The metrics tracker

val to_json : t -> Yojson.Safe.t

Export metrics as JSON

  • parameter t

    The metrics tracker

  • returns

    JSON representation of all metrics