rlg/macros.rs
1// macros.rs
2// Copyright © 2024-2026 RustLogs (RLG). All rights reserved.
3// SPDX-License-Identifier: Apache-2.0
4// SPDX-License-Identifier: MIT
5
6//! Convenience macros for span tracking, latency profiling, and MCP notifications.
7//!
8//! All macros dispatch through the lock-free [`ENGINE`](crate::engine::ENGINE).
9
10/// Execute a block within an OTLP-tagged span.
11///
12/// Emits an OTLP log with a generated `span_id`, increments the active
13/// span counter, runs `$block`, then decrements. Returns the block's value.
14#[macro_export]
15macro_rules! rlg_span {
16 ($name:expr, $block:block) => {{
17 let span_id = $crate::utils::generate_span_id();
18 $crate::engine::ENGINE.inc_spans();
19 $crate::log::Log::info($name)
20 .with("span_id", &span_id)
21 .format($crate::log_format::LogFormat::OTLP)
22 .fire();
23 let result = $block;
24 $crate::engine::ENGINE.dec_spans();
25 result
26 }};
27}
28
29/// Measure wall-clock latency of a block and emit a Logfmt metric.
30///
31/// Captures `Instant::now()` before the block, computes elapsed
32/// microseconds after, and fires a Logfmt log with `latency_us`.
33#[macro_export]
34macro_rules! rlg_time_it {
35 ($action:expr, $block:block) => {{
36 let start = std::time::Instant::now();
37 let result = $block;
38 let elapsed = start.elapsed().as_micros();
39
40 $crate::log::Log::info(&format!("{} completed", $action))
41 .with("latency_us", elapsed as u64)
42 .format($crate::log_format::LogFormat::Logfmt)
43 .fire();
44
45 result
46 }};
47}
48
49/// Emit an MCP-formatted state transition notification.
50///
51/// Use for AI agent orchestration where state changes must be
52/// machine-readable via JSON-RPC 2.0 notification semantics.
53#[macro_export]
54macro_rules! rlg_mcp_notify {
55 ($state_key:expr, $state_val:expr) => {
56 $crate::log::Log::info("State transition")
57 .with($state_key, $state_val)
58 .format($crate::log_format::LogFormat::MCP)
59 .fire();
60 };
61}