micromegas_tracing/macros.rs
1//! Internal macros for tracing functionality (logging, spans, metrics)
2
3#[macro_export]
4macro_rules! static_span_desc {
5 ($var_name:ident, $name:expr) => {
6 static $var_name: $crate::spans::SpanMetadata = $crate::spans::SpanMetadata {
7 name: $name,
8 location: $crate::spans::SpanLocation {
9 lod: $crate::levels::Verbosity::Max,
10 target: module_path!(),
11 module_path: module_path!(),
12 file: file!(),
13 line: line!(),
14 },
15 };
16 };
17}
18
19/// Records a sync span as two thread events
20///
21/// # Examples
22///
23/// ```
24/// use micromegas_tracing::span_scope;
25///
26/// # fn main() {
27/// span_scope!("scope");
28/// # }
29/// ```
30///
31/// With `name =`, the macro is an expression that returns the guard, and the span's end event
32/// carries the properties. The list is the one `log!` takes (literals, `static` values, `%`, `?`
33/// and bare values, and a trailing `..set`); `name` is reserved for the span's name. Add results
34/// later with `set_property`, which wins over a property of the same name given here.
35///
36/// ```
37/// use micromegas_tracing::prelude::*;
38///
39/// # fn main() {
40/// let request = 7;
41/// let mut span = span_scope!(name = "fetch_rows", region = "eu", request = %request);
42/// span.set_property("rows", 42);
43/// # }
44/// ```
45///
46/// Bind the guard to a name: `let _ = span_scope!(name = ..)` drops it at once, like any
47/// `let _`. A bare statement is a compile error under `deny(unused_must_use)`:
48///
49/// ```compile_fail
50/// #![deny(unused_must_use)]
51/// use micromegas_tracing::span_scope;
52///
53/// span_scope!(name = "x");
54/// ```
55///
56/// `name` can't also be a property key:
57///
58/// ```compile_fail
59/// use micromegas_tracing::span_scope;
60///
61/// let _span = span_scope!(name = "x", name = "y");
62/// ```
63#[macro_export]
64macro_rules! span_scope {
65 (name = $name:expr $(, $($rest:tt)*)?) => {
66 $crate::__props!(@m span [scope $name] [] [] [] [] [] $($($rest)*)?)
67 };
68 ($static_var_name:ident, $name:expr) => {
69 $crate::static_span_desc!($static_var_name, $name);
70 let guard_named = $crate::guards::ThreadSpanGuard::new(&$static_var_name);
71 };
72 ($name:expr) => {
73 $crate::span_scope!(_METADATA_NAMED, $name);
74 };
75}
76
77/// Records a span with a name that is determined at runtime.
78/// The span name needs to be statically allocated; use `span_scope_named_dyn!` for a name built
79/// at runtime.
80///
81/// # Examples
82///
83/// ```
84/// use micromegas_tracing::span_scope_named;
85///
86/// # fn get_name() -> &'static str {
87/// # return "name";
88/// # }
89/// #
90/// # fn main() {
91/// span_scope_named!(get_name());
92/// # }
93/// ```
94///
95/// `span_scope_named!(name = get_name(), key = value, ..)` returns a guard whose end event
96/// carries properties; see [`span_scope!`](crate::span_scope!).
97///
98/// ```
99/// use micromegas_tracing::prelude::*;
100///
101/// # fn main() {
102/// let mut span = span_scope_named!(name = "fetch", region = "eu");
103/// span.set_property("rows", 42);
104/// # }
105/// ```
106#[macro_export]
107macro_rules! span_scope_named {
108 (name = $name:expr $(, $($rest:tt)*)?) => {
109 $crate::__props!(@m span [named $name] [] [] [] [] [] $($($rest)*)?)
110 };
111 ($static_var_name:ident, $name:expr) => {
112 static $static_var_name: $crate::spans::SpanLocation = $crate::spans::SpanLocation {
113 lod: $crate::levels::Verbosity::Max,
114 target: module_path!(),
115 module_path: module_path!(),
116 file: file!(),
117 line: line!(),
118 };
119 let guard_named = $crate::guards::ThreadNamedSpanGuard::new(&$static_var_name, $name);
120 };
121 ($name:expr) => {
122 $crate::span_scope_named!(_METADATA_NAMED, $name);
123 };
124}
125
126/// Records a span whose name is built at runtime, such as `format!(..)` or a `&String`.
127/// The name is copied into each block that records one of the span's events, so a high
128/// number of distinct names does not accumulate in memory.
129/// The guard owns the name, which is kept alive until the end of the scope.
130///
131/// # Examples
132///
133/// ```
134/// use micromegas_tracing::span_scope_named_dyn;
135///
136/// # fn main() {
137/// let asset = String::from("hero.png");
138/// span_scope_named_dyn!(format!("load {asset}"));
139/// # }
140/// ```
141///
142/// `span_scope_named_dyn!(name = format!(..), key = value, ..)` returns a guard whose end event
143/// carries properties; see [`span_scope!`](crate::span_scope!).
144///
145/// ```
146/// use micromegas_tracing::prelude::*;
147///
148/// # fn main() {
149/// let asset = String::from("hero.png");
150/// let mut span = span_scope_named_dyn!(name = format!("load {asset}"), kind = "texture");
151/// span.set_property("bytes", 1024);
152/// # }
153/// ```
154#[macro_export]
155macro_rules! span_scope_named_dyn {
156 (name = $name:expr $(, $($rest:tt)*)?) => {
157 $crate::__props!(@m span [named_dyn $name] [] [] [] [] [] $($($rest)*)?)
158 };
159 ($static_var_name:ident, $name:expr) => {
160 static $static_var_name: $crate::spans::SpanLocation = $crate::spans::SpanLocation {
161 lod: $crate::levels::Verbosity::Max,
162 target: module_path!(),
163 module_path: module_path!(),
164 file: file!(),
165 line: line!(),
166 };
167 let guard_named = $crate::guards::ThreadNamedSpanGuard::with_name(
168 &$static_var_name,
169 $crate::spans::DynSpanName($name),
170 );
171 };
172 ($name:expr) => {
173 $crate::span_scope_named_dyn!(_METADATA_NAMED, $name);
174 };
175}
176
177/// Creates a static SpanLocation for use with named async spans.
178/// This is an internal implementation detail - users should use `instrument_named!` instead.
179///
180/// # Examples
181///
182/// ```
183/// use micromegas_tracing::prelude::*;
184///
185/// # #[tokio::main]
186/// # async fn main() {
187/// // Don't use this directly - use instrument_named! instead
188/// static_span_location!(LOCATION);
189/// // Users should prefer: instrument_named!(future, "name")
190/// # }
191/// ```
192#[macro_export]
193macro_rules! static_span_location {
194 ($var_name:ident) => {
195 static $var_name: $crate::spans::SpanLocation = $crate::spans::SpanLocation {
196 lod: $crate::levels::Verbosity::Max,
197 target: module_path!(),
198 module_path: module_path!(),
199 file: file!(),
200 line: line!(),
201 };
202 };
203}
204
205/// Instruments an async block with a named span using a static string.
206/// This creates both the SpanLocation and instruments the future in one macro call.
207///
208/// # Examples
209///
210/// ```
211/// use micromegas_tracing::prelude::*;
212///
213/// # #[tokio::main]
214/// # async fn main() {
215/// let result = span_async_named!("database_query", async {
216/// // async work here
217/// 42
218/// }).await;
219/// # }
220/// ```
221///
222/// A trailing closure receives the output and a `&mut SpanProperties` to set end properties on:
223///
224/// ```
225/// use micromegas_tracing::prelude::*;
226///
227/// # #[tokio::main]
228/// # async fn main() {
229/// let rows = span_async_named!("database_query", async { vec![1, 2] }, |rows, span| {
230/// span.set_property("rows", rows.len());
231/// }).await;
232/// # }
233/// ```
234#[macro_export]
235macro_rules! span_async_named {
236 ($name:expr, $async_block:expr) => {{
237 use $crate::spans::InstrumentFuture as _;
238 $crate::static_span_location!(_ASYNC_LOCATION);
239 $async_block.__instrument_named_internal(&_ASYNC_LOCATION, $name)
240 }};
241 ($name:expr, $async_block:expr, $on_end:expr) => {{
242 use $crate::spans::InstrumentFuture as _;
243 $crate::static_span_location!(_ASYNC_LOCATION);
244 $async_block.__instrument_named_with_internal(&_ASYNC_LOCATION, $name, $on_end)
245 }};
246}
247
248/// Instruments a future with a named span.
249/// Usage: `instrument_named!(future, "span_name")`
250///
251/// # Examples
252///
253/// ```
254/// use micromegas_tracing::prelude::*;
255///
256/// # #[tokio::main]
257/// # async fn main() {
258/// let future = async { 42 };
259/// let result = instrument_named!(future, "operation_name").await;
260/// # }
261/// ```
262///
263/// A trailing closure receives the output and a `&mut SpanProperties` to set end properties on:
264///
265/// ```
266/// use micromegas_tracing::prelude::*;
267///
268/// # #[tokio::main]
269/// # async fn main() {
270/// let rows = instrument_named!(async { vec![1, 2] }, "fetch", |rows, span| {
271/// span.set_property("rows", rows.len());
272/// })
273/// .await;
274/// # }
275/// ```
276#[macro_export]
277macro_rules! instrument_named {
278 ($future:expr, $name:expr) => {{
279 use $crate::spans::InstrumentFuture as _;
280 $crate::static_span_location!(_INSTRUMENT_LOCATION);
281 $future.__instrument_named_internal(&_INSTRUMENT_LOCATION, $name)
282 }};
283 ($future:expr, $name:expr, $on_end:expr) => {{
284 use $crate::spans::InstrumentFuture as _;
285 $crate::static_span_location!(_INSTRUMENT_LOCATION);
286 $future.__instrument_named_with_internal(&_INSTRUMENT_LOCATION, $name, $on_end)
287 }};
288}
289
290/// Instruments an async block with a named span whose name is built at runtime.
291/// The future owns the name: pass a `String` or `Arc<str>` to keep the future `'static`.
292///
293/// # Examples
294///
295/// ```
296/// use micromegas_tracing::prelude::*;
297///
298/// # #[tokio::main]
299/// # async fn main() {
300/// let id = 7;
301/// let result = span_async_named_dyn!(format!("query {id}"), async {
302/// 42
303/// }).await;
304/// # }
305/// ```
306///
307/// A trailing closure receives the output and a `&mut SpanProperties` to set end properties on:
308///
309/// ```
310/// use micromegas_tracing::prelude::*;
311///
312/// # #[tokio::main]
313/// # async fn main() {
314/// let id = 7;
315/// let n = span_async_named_dyn!(format!("query {id}"), async { 42 }, |n, span| {
316/// span.set_property("n", n);
317/// }).await;
318/// # }
319/// ```
320#[macro_export]
321macro_rules! span_async_named_dyn {
322 ($name:expr, $async_block:expr) => {{
323 use $crate::spans::InstrumentFuture as _;
324 $crate::static_span_location!(_ASYNC_LOCATION);
325 $async_block.__instrument_named_dyn_internal(&_ASYNC_LOCATION, $name)
326 }};
327 ($name:expr, $async_block:expr, $on_end:expr) => {{
328 use $crate::spans::InstrumentFuture as _;
329 $crate::static_span_location!(_ASYNC_LOCATION);
330 $async_block.__instrument_named_dyn_with_internal(&_ASYNC_LOCATION, $name, $on_end)
331 }};
332}
333
334/// Instruments a future with a named span whose name is built at runtime.
335/// The future owns the name: pass a `String` or `Arc<str>` to keep the future `'static`.
336/// Usage: `instrument_named_dyn!(future, format!("op {id}"))`
337///
338/// # Examples
339///
340/// ```
341/// use micromegas_tracing::prelude::*;
342///
343/// # #[tokio::main]
344/// # async fn main() {
345/// let future = async { 42 };
346/// let result = instrument_named_dyn!(future, format!("operation {}", 1)).await;
347/// # }
348/// ```
349///
350/// A trailing closure receives the output and a `&mut SpanProperties` to set end properties on:
351///
352/// ```
353/// use micromegas_tracing::prelude::*;
354///
355/// # #[tokio::main]
356/// # async fn main() {
357/// let n = instrument_named_dyn!(async { 42 }, format!("operation {}", 1), |n, span| {
358/// span.set_property("n", n);
359/// })
360/// .await;
361/// # }
362/// ```
363#[macro_export]
364macro_rules! instrument_named_dyn {
365 ($future:expr, $name:expr) => {{
366 use $crate::spans::InstrumentFuture as _;
367 $crate::static_span_location!(_INSTRUMENT_LOCATION);
368 $future.__instrument_named_dyn_internal(&_INSTRUMENT_LOCATION, $name)
369 }};
370 ($future:expr, $name:expr, $on_end:expr) => {{
371 use $crate::spans::InstrumentFuture as _;
372 $crate::static_span_location!(_INSTRUMENT_LOCATION);
373 $future.__instrument_named_dyn_with_internal(&_INSTRUMENT_LOCATION, $name, $on_end)
374 }};
375}
376
377/// Records a integer metric. Use [`imetric_dyn!`](crate::imetric_dyn!) when the name or unit is built at run time.
378///
379/// # Examples
380///
381/// ```
382/// use micromegas_tracing::imetric;
383///
384/// # fn main() {
385/// #
386/// imetric!("Frame Time", "ticks", 1000);
387/// # }
388/// ```
389///
390/// Properties go between the unit and the value, as `key = value` pairs. A key is an
391/// identifier or a string literal. Literal values are interned once per callsite, unless a `..set`
392/// is spread without a `static` value, in which case the literals are copied into the block
393/// (the spread set's own values are not); any other value is attached to the measure and copied
394/// into the current block. A
395/// bare value must implement [`PropertyValue`](crate::property_value::PropertyValue) (strings
396/// do); use `%value` (`Display`) or `?value` (`Debug`) for the rest, at the cost of one `String`
397/// allocation.
398///
399/// ```
400/// use micromegas_tracing::prelude::*;
401///
402/// # fn main() {
403/// let correlation_id = String::from("c0ffee");
404/// let rows = 3;
405/// imetric!("rows_fetched", "count", correlation_id = correlation_id, region = "eu", rows = %rows, 3);
406/// imetric!("rows_fetched", "count", "http.method" = "GET", 3);
407/// # }
408/// ```
409///
410/// In a call with properties, a `{key}` placeholder whose name is a property key refers to that
411/// property's value (evaluated once), not to a local of the same name; every other placeholder
412/// keeps its usual meaning. When every placeholder is a plain `{key}` over a `%`, bare, `static`,
413/// or string, char, bool or integer literal property, or a `{key:?}` over a `?` property, and
414/// the call has no other format arguments, the process doesn't format the message at all: it
415/// stores the format string with the properties, and analytics renders it. That is the cheapest
416/// way to put a property in the message, and it is smaller in the block. A placeholder with a
417/// spec (`{key:>8}`), a `{key}` over a `?` property, a float or negated literal, a positional
418/// argument, or a name that isn't a property is formatted in the process as before.
419/// Property names are case-insensitive, so a placeholder matching two keys is a compile error,
420/// and a placeholder only binds a key spelled exactly like it.
421///
422/// ```
423/// use micromegas_tracing::prelude::*;
424///
425/// # fn main() {
426/// let (user, rows) = ("alice", 3);
427/// info!(user = user, rows = %rows, "{user} fetched {rows} rows");
428/// # }
429/// ```
430///
431/// A placeholder that matches two keys is ambiguous, so it doesn't compile:
432///
433/// ```compile_fail
434/// use micromegas_tracing::prelude::*;
435///
436/// let (a, b) = ("1", "2");
437/// info!(user = %a, User = %b, "{user}");
438/// ```
439///
440/// A literal or `static` property is recorded once per callsite and never formatted per call, so
441/// it can't take a format spec or `{key:?}`; bind the value to a differently named local and
442/// format that instead:
443///
444/// ```compile_fail
445/// use micromegas_tracing::prelude::*;
446///
447/// let x: &'static str = "x";
448/// info!(l = static x, "{l:?}");
449/// ```
450///
451/// ```compile_fail
452/// use micromegas_tracing::prelude::*;
453///
454/// info!(n = 1, "{n:>8}");
455/// ```
456///
457/// A precomputed `&'static PropertySet` is spread with `..set`. It must come last in the
458/// property list, and `key = value` pairs override its entries:
459///
460/// ```
461/// use micromegas_tracing::prelude::*;
462/// use micromegas_tracing::property_set::{Property, PropertySet};
463///
464/// # fn main() {
465/// let set = PropertySet::find_or_create(vec![Property::new("region", "eu")]);
466/// imetric!("rows_fetched", "count", ..set, 3);
467/// imetric!("rows_fetched", "count", correlation_id = "c0ffee", ..set, 3);
468/// # }
469/// ```
470///
471/// `target: "name"` replaces the module path as the target of the metric:
472///
473/// ```
474/// use micromegas_tracing::prelude::*;
475///
476/// # fn main() {
477/// imetric!(target: "my_crate::cache", "hits", "count", kind = "disk", 1);
478/// # }
479/// ```
480///
481/// `key = static expr` takes a `&'static str` chosen at runtime, from a small closed set (a
482/// label or an enum variant name, for example). Each distinct tuple of static values is interned
483/// once per callsite and then looked up, a few nanoseconds more than a `..set` spread and far
484/// cheaper than a dynamic value. Every distinct value is kept forever, so the cardinality
485/// contract of `PropertySet` applies: never use it for ids. It mixes freely with literals,
486/// dynamic values and a trailing `..set`. Among literals and static values the last one wins
487/// (case-insensitive), a dynamic value beats both, and any pair overrides a `..set` entry. With
488/// `..set` and a static value in the same call, literals and static values are interned over the
489/// set, so dynamic values beat them whatever the order.
490///
491/// ```
492/// use micromegas_tracing::prelude::*;
493///
494/// # fn main() {
495/// let label: &'static str = "alpha";
496/// imetric!("rows_fetched", "count", prefix = static label, tier = "ram", 3);
497/// fmetric!("fetch_ms", "ms", prefix = static label, 1.5);
498/// # }
499/// ```
500///
501/// The value must be `'static`; a borrowed string is a compile error:
502///
503/// ```compile_fail
504/// use micromegas_tracing::prelude::*;
505///
506/// let s = String::from("alpha");
507/// imetric!("rows_fetched", "count", prefix = static s.as_str(), 3);
508/// ```
509///
510/// `static` doesn't combine with `%` or `?`:
511///
512/// ```compile_fail
513/// use micromegas_tracing::prelude::*;
514///
515/// imetric!("rows_fetched", "count", prefix = static %"x", 3);
516/// ```
517///
518/// `target`, `name` and `unit` are reserved keys, because analytics treats them as column
519/// overrides. They can still be set through a `..set` spread:
520///
521/// ```compile_fail
522/// use micromegas_tracing::prelude::*;
523///
524/// imetric!("rows_fetched", "count", unit = "rows", 3);
525/// ```
526///
527/// A literal value goes through `concat!`, so `1_000` is recorded as "1000" and `0x10` as "16",
528/// while a float keeps its spelling (`0.50` stays "0.50"); `%value` uses `Display` instead.
529///
530/// A bare integer needs `%`:
531///
532/// ```compile_fail
533/// use micromegas_tracing::prelude::*;
534///
535/// let n = 3_u32;
536/// imetric!("rows_fetched", "count", rows = n, 3);
537/// ```
538///
539/// A bare negated expression has no `PropertyValue` impl either:
540///
541/// ```compile_fail
542/// use micromegas_tracing::prelude::*;
543///
544/// let n = 3_i32;
545/// imetric!("rows_fetched", "count", delta = -n, 3);
546/// ```
547///
548/// `..set` can't be followed by other entries, and appears at most once:
549///
550/// ```compile_fail
551/// use micromegas_tracing::prelude::*;
552/// use micromegas_tracing::property_set::PropertySet;
553///
554/// let set = PropertySet::empty();
555/// imetric!("rows_fetched", "count", ..set, kind = "a", 3);
556/// ```
557///
558/// ```compile_fail
559/// use micromegas_tracing::prelude::*;
560/// use micromegas_tracing::property_set::PropertySet;
561///
562/// let set = PropertySet::empty();
563/// imetric!("rows_fetched", "count", ..set, ..set, 3);
564/// ```
565#[macro_export]
566macro_rules! imetric {
567 (target: $target:expr, $name:expr, $unit:expr, $($rest:tt)+) => {
568 $crate::__props!(@m metric
569 [$name, $unit, $target, int_metric, tagged_integer_metric_dyn]
570 [] [] [] [] [] $($rest)+)
571 };
572 ($name:expr, $unit:expr, $($rest:tt)+) => {
573 $crate::__props!(@m metric
574 [$name, $unit, module_path!(), int_metric, tagged_integer_metric_dyn]
575 [] [] [] [] [] $($rest)+)
576 };
577}
578
579/// Records a float metric.
580///
581/// # Examples
582///
583/// ```
584/// use micromegas_tracing::fmetric;
585///
586/// # fn main() {
587/// #
588/// fmetric!("Frame Time", "ticks", 1000.0);
589/// # }
590/// ```
591///
592/// Properties are `key = value` pairs between the unit and the value, as with [`imetric!`]:
593///
594/// ```
595/// use micromegas_tracing::prelude::*;
596///
597/// # fn main() {
598/// let elapsed_ms = 12.5;
599/// fmetric!("fetch_ms", "ms", "http.method" = "GET", elapsed_ms);
600/// fmetric!("delta", "ms", -elapsed_ms);
601/// # }
602/// ```
603#[macro_export]
604macro_rules! fmetric {
605 (target: $target:expr, $name:expr, $unit:expr, $($rest:tt)+) => {
606 $crate::__props!(@m metric
607 [$name, $unit, $target, float_metric, tagged_float_metric_dyn]
608 [] [] [] [] [] $($rest)+)
609 };
610 ($name:expr, $unit:expr, $($rest:tt)+) => {
611 $crate::__props!(@m metric
612 [$name, $unit, module_path!(), float_metric, tagged_float_metric_dyn]
613 [] [] [] [] [] $($rest)+)
614 };
615}
616
617/// Records an integer metric whose name or unit is only known at run time.
618///
619/// `name` and `unit` can be anything that implements `AsRef<str>`: a literal, a `&String`,
620/// `format!(..)` or an `Arc<str>`. They are copied into the current block once per distinct
621/// value, so nothing is retained for the life of the process. The rest of the grammar is the
622/// one of [`imetric!`].
623///
624/// Every distinct name is a distinct series for queries and materialized views, so the names
625/// should still come from a bounded set: deduplication within a block only bounds the cost on
626/// the wire. `name` and `unit` also appear in the `properties` column of the measure.
627///
628/// ```
629/// use micromegas_tracing::prelude::*;
630///
631/// # fn main() {
632/// let queue = "render";
633/// let depth = 3;
634/// imetric_dyn!(format!("queue.{queue}.depth"), "count", depth);
635/// imetric_dyn!(target: "my_crate::io", String::from("bytes_read"), "bytes", "http.method" = "GET", 512);
636/// # }
637/// ```
638///
639/// `name` and `unit` are reserved keys, as with [`imetric!`]:
640///
641/// ```compile_fail
642/// use micromegas_tracing::prelude::*;
643///
644/// imetric_dyn!("rows_fetched", "count", name = "other", 3);
645/// ```
646///
647/// `..set` must be the last property:
648///
649/// ```compile_fail
650/// use micromegas_tracing::prelude::*;
651/// use micromegas_tracing::property_set::PropertySet;
652///
653/// let set = PropertySet::empty();
654/// imetric_dyn!("rows_fetched", "count", ..set, kind = "a", 3);
655/// ```
656#[macro_export]
657macro_rules! imetric_dyn {
658 (target: $target:expr, $name:expr, $unit:expr, $($rest:tt)+) => {
659 $crate::__props!(@m metric
660 [$name, $unit, $target, int_metric, tagged_integer_metric_dyn, dynamic]
661 [] [] [] [] [] $($rest)+)
662 };
663 ($name:expr, $unit:expr, $($rest:tt)+) => {
664 $crate::__props!(@m metric
665 [$name, $unit, module_path!(), int_metric, tagged_integer_metric_dyn, dynamic]
666 [] [] [] [] [] $($rest)+)
667 };
668}
669
670/// Records a float metric whose name or unit is only known at run time.
671///
672/// Same as [`imetric_dyn!`](crate::imetric_dyn!), including the cardinality caveat, for a floating-point value.
673///
674/// ```
675/// use micromegas_tracing::prelude::*;
676///
677/// # fn main() {
678/// let (name, unit) = (String::from("http.latency"), "ms");
679/// let elapsed = 12.5;
680/// fmetric_dyn!(target: "my_crate::io", &name, unit, "http.method" = "GET", elapsed);
681/// # }
682/// ```
683///
684/// `name` and `unit` are reserved keys, as with [`fmetric!`]:
685///
686/// ```compile_fail
687/// use micromegas_tracing::prelude::*;
688///
689/// fmetric_dyn!("latency", "ms", unit = "s", 1.0);
690/// ```
691#[macro_export]
692macro_rules! fmetric_dyn {
693 (target: $target:expr, $name:expr, $unit:expr, $($rest:tt)+) => {
694 $crate::__props!(@m metric
695 [$name, $unit, $target, float_metric, tagged_float_metric_dyn, dynamic]
696 [] [] [] [] [] $($rest)+)
697 };
698 ($name:expr, $unit:expr, $($rest:tt)+) => {
699 $crate::__props!(@m metric
700 [$name, $unit, module_path!(), float_metric, tagged_float_metric_dyn, dynamic]
701 [] [] [] [] [] $($rest)+)
702 };
703}
704
705/// The standard logging macro.
706///
707/// This macro will generically log with the specified `Level` and `format!`
708/// based argument list.
709///
710/// # Examples
711///
712/// ```
713/// use micromegas_tracing::prelude::*;
714///
715/// # fn main() {
716/// let data = (42, "Forty-two");
717/// let private_data = "private";
718///
719/// log!(Level::Error, "Received errors: {}, {}", data.0, data.1);
720/// log!(target: "app_events", Level::Warn, "App warning: {}, {}, {}",
721/// data.0, data.1, private_data);
722/// # }
723/// ```
724///
725/// Properties go before the format string, as `key = value` pairs. A key is an identifier or a
726/// string literal. A literal value is interned once per callsite, unless a `..set` is spread
727/// without a `static` value, in which case the literals are copied into the block (the spread
728/// set's own values are not). Any other value (a request or correlation id, for example) is
729/// copied into the current block, so nothing leaks. A bare value must implement
730/// [`PropertyValue`](crate::property_value::PropertyValue) (strings do); use
731/// `%value` (`Display`) or `?value` (`Debug`) for the rest, at the cost of one `String`
732/// allocation. Dynamic values are only evaluated when the entry is enabled.
733///
734/// ```
735/// use micromegas_tracing::prelude::*;
736///
737/// # fn main() {
738/// let correlation_id = String::from("c0ffee");
739/// let rows = 3;
740/// info!(correlation_id = correlation_id, region = "eu", rows = %rows, "fetched {rows} rows");
741/// info!(target: "app_events", "http.method" = "GET", "request done");
742/// # }
743/// ```
744///
745/// A precomputed `&'static PropertySet` is spread with `..set`. It must come last in the
746/// property list, and `key = value` pairs override its entries:
747///
748/// ```
749/// use micromegas_tracing::prelude::*;
750/// use micromegas_tracing::property_set::{Property, PropertySet};
751///
752/// # fn main() {
753/// let set = PropertySet::find_or_create(vec![Property::new("region", "eu")]);
754/// info!(..set, "from a set");
755/// info!(correlation_id = "c0ffee", ..set, "from a set and a pair");
756/// # }
757/// ```
758///
759/// `key = static expr` takes a `&'static str` chosen at runtime, from a small closed set (a
760/// label or an enum variant name, for example). Each distinct tuple of static values is interned
761/// once per callsite and then looked up, a few nanoseconds more than a `..set` spread and far
762/// cheaper than a dynamic value. Every distinct value is kept forever, so the cardinality
763/// contract of `PropertySet` applies: never use it for ids. It mixes freely with literals,
764/// dynamic values and a trailing `..set`. Among literals and static values the last one wins
765/// (case-insensitive), a dynamic value beats both, and any pair overrides a `..set` entry. With
766/// `..set` and a static value in the same call, literals and static values are interned over the
767/// set, so dynamic values beat them whatever the order. A static expression is only evaluated
768/// when the entry is enabled.
769///
770/// ```
771/// use micromegas_tracing::prelude::*;
772///
773/// # fn main() {
774/// let label: &'static str = "alpha";
775/// info!(prefix = static label, request = %"id", "fetched");
776/// # use micromegas_tracing::property_set::PropertySet;
777/// info!(prefix = static label, kind = "a", ..PropertySet::empty(), "with a set");
778/// # }
779/// ```
780///
781/// The value must be `'static`; a borrowed string is a compile error:
782///
783/// ```compile_fail
784/// use micromegas_tracing::prelude::*;
785///
786/// let s = String::from("alpha");
787/// info!(prefix = static s.as_str(), "fetched");
788/// ```
789///
790/// `static` doesn't combine with `%` or `?`:
791///
792/// ```compile_fail
793/// use micromegas_tracing::prelude::*;
794///
795/// info!(prefix = static %"x", "fetched");
796/// ```
797///
798/// `level` and `target` are reserved keys, because analytics treats them as column overrides.
799/// They can still be set through a `..set` spread:
800///
801/// ```compile_fail
802/// use micromegas_tracing::prelude::*;
803///
804/// info!(level = "debug", "message");
805/// ```
806///
807/// A literal value goes through `concat!`, so `1_000` is recorded as "1000" and `0x10` as "16",
808/// while a float keeps its spelling (`0.50` stays "0.50"); `%value` uses `Display` instead.
809///
810/// A bare integer needs `%`:
811///
812/// ```compile_fail
813/// use micromegas_tracing::prelude::*;
814///
815/// let n = 3_u32;
816/// info!(rows = n, "fetched");
817/// ```
818///
819/// A bare negated expression has no `PropertyValue` impl either:
820///
821/// ```compile_fail
822/// use micromegas_tracing::prelude::*;
823///
824/// let n = 3_i32;
825/// info!(delta = -n, "fetched");
826/// ```
827///
828/// `..set` can't be followed by other entries, and appears at most once:
829///
830/// ```compile_fail
831/// use micromegas_tracing::prelude::*;
832/// use micromegas_tracing::property_set::PropertySet;
833///
834/// let set = PropertySet::empty();
835/// info!(..set, kind = "a", "message");
836/// ```
837///
838/// ```compile_fail
839/// use micromegas_tracing::prelude::*;
840/// use micromegas_tracing::property_set::PropertySet;
841///
842/// let set = PropertySet::empty();
843/// info!(..set, ..set, "message");
844/// ```
845#[macro_export]
846macro_rules! log {
847 (target: $target:expr, $lvl:expr, $($rest:tt)+) => (
848 $crate::__props!(@m log [$target, $lvl] [] [] [] [] [] $($rest)+)
849 );
850 ($lvl:expr, $($rest:tt)+) => (
851 $crate::log!(target: $crate::__log_module_path!(), $lvl, $($rest)+)
852 );
853}
854
855/// Muncher behind the property lists of `log!`, `imetric!` and `fmetric!`.
856///
857/// Accumulators, in order: literal and static pairs `(key, lit|stat, (value))` for the
858/// per-callsite set, dynamic entries `(key, kind, value)`, every non-static entry in source
859/// order (used when a `..set` is spread without a static value, so that the last pair wins),
860/// the spread set, and `[static]` once a `static` value was seen.
861#[doc(hidden)]
862#[macro_export]
863macro_rules! __props {
864 // Span property lists have no trailing format string or value, so they can end here, and can
865 // end on a `..set` with nothing after it.
866 (@m span $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt) => {
867 $crate::__props!(@end span $ctx $s $d $a $set $t)
868 };
869 (@m span $ctx:tt $s:tt $d:tt $a:tt [] $t:tt .. $new_set:expr $(,)?) => {
870 $crate::__props!(@end span $ctx $s $d $a [$new_set] $t)
871 };
872 // `..set` is only accepted as the last property.
873 (@m $kind:ident $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt
874 .. $new_set:expr, $k:tt = $($x:tt)*) => {
875 compile_error!("`..set` must be the last entry of the property list")
876 };
877 (@m $kind:ident $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt
878 .. $new_set:expr, .. $($x:tt)*) => {
879 compile_error!("`..set` can only appear once, as the last entry of the property list")
880 };
881 (@m $kind:ident $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt
882 .. $new_set:expr, $($rest:tt)+) => {
883 $crate::__props!(@end $kind $ctx $s $d $a [$new_set] $t $($rest)+)
884 };
885 // `static` never starts a literal or a bare expression, so this arm can come first.
886 (@m $kind:ident $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] $set:tt $t:tt
887 $k:tt = static $v:expr $(, $($rest:tt)*)?) => {
888 $crate::__props!(@m $kind $ctx
889 [$($s)* ($k, stat, ($v))] [$($d)*] [$($a)*] $set [static] $($($rest)*)?)
890 };
891 // The negative literal arm precedes the `-` fallback, which precedes the plain literal arm:
892 // `$v:literal` is a hard parse error on `-x`.
893 (@m $kind:ident $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] $set:tt $t:tt
894 $k:tt = - $v:literal $(, $($rest:tt)*)?) => {
895 $crate::__props!(@m $kind $ctx
896 [$($s)* ($k, lit, (concat!("-", $v)))] [$($d)*]
897 [$($a)* ($k, lit, (concat!("-", $v)))] $set $t $($($rest)*)?)
898 };
899 (@m $kind:ident $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt
900 $k:tt = - $($rest:tt)*) => {
901 $crate::__props!(@e $kind $ctx $s $d $a $set $t $k = - $($rest)*)
902 };
903 (@m $kind:ident $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] $set:tt $t:tt
904 $k:tt = % $v:expr $(, $($rest:tt)*)?) => {
905 $crate::__props!(@m $kind $ctx
906 [$($s)*] [$($d)* ($k, disp, $v)] [$($a)* ($k, disp, $v)] $set $t $($($rest)*)?)
907 };
908 (@m $kind:ident $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] $set:tt $t:tt
909 $k:tt = ? $v:expr $(, $($rest:tt)*)?) => {
910 $crate::__props!(@m $kind $ctx
911 [$($s)*] [$($d)* ($k, dbg, $v)] [$($a)* ($k, dbg, $v)] $set $t $($($rest)*)?)
912 };
913 (@m $kind:ident $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] $set:tt $t:tt
914 $k:tt = $v:literal $(, $($rest:tt)*)?) => {
915 $crate::__props!(@m $kind $ctx
916 [$($s)* ($k, lit, (concat!($v)))] [$($d)*]
917 [$($a)* ($k, lit, (concat!($v)))] $set $t $($($rest)*)?)
918 };
919 (@m $kind:ident $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt
920 $k:tt = $($rest:tt)+) => {
921 $crate::__props!(@e $kind $ctx $s $d $a $set $t $k = $($rest)+)
922 };
923 // A bare value
924 (@e $kind:ident $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] $set:tt $t:tt
925 $k:tt = $v:expr $(, $($rest:tt)*)?) => {
926 $crate::__props!(@m $kind $ctx
927 [$($s)*] [$($d)* ($k, bare, $v)] [$($a)* ($k, bare, $v)] $set $t $($($rest)*)?)
928 };
929 // The end of the property list: a format string for logs, a value for metrics.
930 (@m log $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt) => {
931 compile_error!("log macros require a format string")
932 };
933 (@m log $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt $($fmt:tt)+) => {
934 $crate::__props!(@end log $ctx $s $d $a $set $t $($fmt)+)
935 };
936 (@m metric $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt $value:expr $(,)?) => {
937 $crate::__props!(@end metric $ctx $s $d $a $set $t $value)
938 };
939
940 // `__log_impl!` picks the call shape and how the message is stored.
941 (@end log $ctx:tt $s:tt $d:tt $a:tt $set:tt $t:tt $($fmt:tt)+) => {
942 $crate::__log_impl!($crate $ctx $s $d $a $set $t $($fmt)+)
943 };
944
945 (@end metric $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [] [static]
946 $value:expr $(,)?) => {
947 $crate::__metric_call!(tagged $ctx
948 $crate::__static_set!(metric [] $($s)+),
949 [$($d)*], $value)
950 };
951 (@end metric $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [$set:tt] [static]
952 $value:expr $(,)?) => {
953 $crate::__metric_call!(tagged $ctx
954 $crate::__static_set!(metric [$set] $($s)+),
955 [$($d)*], $value)
956 };
957
958 (@end metric $ctx:tt [] [] [] [] [] $value:expr) => {
959 $crate::__metric_call!(plain $ctx $value)
960 };
961
962 // A span's static set goes to its guard: the callsite literals, or the literals and static
963 // values over the spread set, or the spread set alone.
964 (@end span $ctx:tt [] [$($d:tt)*] [$($a:tt)*] [] []) => {
965 $crate::__span_guard_call!($ctx $crate::property_set::PropertySet::empty(), [$($d)*])
966 };
967 (@end span $ctx:tt [] [$($d:tt)*] [$($a:tt)*] [$set:tt] []) => {
968 $crate::__span_guard_call!($ctx $set, [$($d)*])
969 };
970 (@end span $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [] [static]) => {
971 $crate::__span_guard_call!($ctx $crate::__static_set!(span [] $($s)+), [$($d)*])
972 };
973 (@end span $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [$set:tt] [static]) => {
974 $crate::__span_guard_call!($ctx $crate::__static_set!(span [$set] $($s)+), [$($d)*])
975 };
976 (@end span $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [] []) => {
977 $crate::__span_guard_call!($ctx $crate::__callsite_set!(span $($s)+), [$($d)*])
978 };
979 (@end span $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [$set:tt] []) => {
980 $crate::__span_guard_call!($ctx $crate::__static_set!(span [$set] $($s)+), [$($d)*])
981 };
982 (@end metric $ctx:tt [$($s:tt)*] [$($d:tt)*] [$($a:tt)*] [$set:tt] [] $value:expr $(,)?) => {
983 $crate::__metric_call!(tagged $ctx $set, [$($a)*], $value)
984 };
985 (@end metric $ctx:tt [$($s:tt)+] [$($d:tt)*] [$($a:tt)*] [] [] $value:expr) => {
986 $crate::__metric_call!(tagged $ctx
987 $crate::__callsite_set!(metric $($s)+), [$($d)*], $value)
988 };
989 (@end metric $ctx:tt [] [$($d:tt)+] [$($a:tt)*] [] [] $value:expr) => {
990 $crate::__metric_call!(tagged $ctx
991 $crate::property_set::PropertySet::empty(), [$($d)+], $value)
992 };
993}
994
995#[doc(hidden)]
996#[macro_export]
997macro_rules! __metric_call {
998 (plain [$name:expr, $unit:expr, $target:expr, $plain:ident, $dynf:ident] $value:expr) => {{
999 static METRIC_METADATA: $crate::metrics::StaticMetricMetadata =
1000 $crate::metrics::StaticMetricMetadata {
1001 lod: $crate::levels::Verbosity::Max,
1002 name: $name,
1003 unit: $unit,
1004 target: $target,
1005 file: file!(),
1006 line: line!(),
1007 };
1008 $crate::dispatch::$plain(&METRIC_METADATA, $value);
1009 }};
1010 (tagged [$name:expr, $unit:expr, $target:expr, $plain:ident, $dynf:ident]
1011 $set:expr, [$($slice:tt)*], $value:expr) => {{
1012 static METRIC_METADATA: $crate::metrics::StaticMetricMetadata =
1013 $crate::metrics::StaticMetricMetadata {
1014 lod: $crate::levels::Verbosity::Max,
1015 name: $name,
1016 unit: $unit,
1017 target: $target,
1018 file: file!(),
1019 line: line!(),
1020 };
1021 $crate::dispatch::$dynf(
1022 &METRIC_METADATA,
1023 $set,
1024 $crate::__dyn_slice!(metric $($slice)*),
1025 $value,
1026 );
1027 }};
1028 // Runtime name and unit: they travel as the `name` and `unit` property overrides.
1029 (plain [$name:expr, $unit:expr, $target:expr, $plain:ident, $dynf:ident, dynamic]
1030 $value:expr) => {
1031 $crate::__metric_call!(tagged [$name, $unit, $target, $plain, $dynf, dynamic]
1032 $crate::property_set::PropertySet::empty(), [], $value)
1033 };
1034 (tagged [$name:expr, $unit:expr, $target:expr, $plain:ident, $dynf:ident, dynamic]
1035 $set:expr, [$($slice:tt)*], $value:expr) => {{
1036 static METRIC_METADATA: $crate::metrics::StaticMetricMetadata =
1037 $crate::metrics::StaticMetricMetadata {
1038 lod: $crate::levels::Verbosity::Max,
1039 name: "",
1040 unit: "",
1041 target: $target,
1042 file: file!(),
1043 line: line!(),
1044 };
1045 $crate::dispatch::$dynf(
1046 &METRIC_METADATA,
1047 $set,
1048 $crate::__dyn_slice!(metric $($slice)* ;
1049 $crate::property_set::DynProperty::new(
1050 "name",
1051 ::std::convert::AsRef::<str>::as_ref(&$name),
1052 ),
1053 $crate::property_set::DynProperty::new(
1054 "unit",
1055 ::std::convert::AsRef::<str>::as_ref(&$unit),
1056 )
1057 ),
1058 $value,
1059 );
1060 }};
1061}
1062
1063/// Builds the guard of a span with properties. The dynamic values are formatted before the begin
1064/// event, so that formatting is not charged to the span.
1065#[doc(hidden)]
1066#[macro_export]
1067macro_rules! __span_guard_call {
1068 ([scope $name:expr] $set:expr, [$($d:tt)*]) => {{
1069 $crate::static_span_desc!(_METADATA_NAMED, $name);
1070 let mut properties = $crate::spans::SpanProperties::new($set);
1071 $crate::__span_set_properties!(properties $($d)*);
1072 $crate::guards::ThreadSpanGuard::with_properties(&_METADATA_NAMED, properties)
1073 }};
1074 ([future $name:expr, $future:expr] $set:expr, [$($d:tt)*]) => {{
1075 $crate::static_span_desc!(_METADATA_NAMED, $name);
1076 let mut properties = $crate::spans::SpanProperties::new($set);
1077 $crate::__span_set_properties!(properties $($d)*);
1078 $crate::spans::InstrumentedFuture::with_properties($future, &_METADATA_NAMED, properties)
1079 }};
1080 ([named $name:expr] $set:expr, [$($d:tt)*]) => {{
1081 $crate::__span_guard_call!(@loc _LOCATION);
1082 let mut properties = $crate::spans::SpanProperties::new($set);
1083 $crate::__span_set_properties!(properties $($d)*);
1084 $crate::guards::ThreadNamedSpanGuard::with_properties(
1085 &_LOCATION,
1086 $crate::spans::StaticSpanName($name),
1087 properties,
1088 )
1089 }};
1090 ([named_dyn $name:expr] $set:expr, [$($d:tt)*]) => {{
1091 $crate::__span_guard_call!(@loc _LOCATION);
1092 let mut properties = $crate::spans::SpanProperties::new($set);
1093 $crate::__span_set_properties!(properties $($d)*);
1094 $crate::guards::ThreadNamedSpanGuard::with_properties(
1095 &_LOCATION,
1096 $crate::spans::DynSpanName($name),
1097 properties,
1098 )
1099 }};
1100 (@loc $var:ident) => {
1101 static $var: $crate::spans::SpanLocation = $crate::spans::SpanLocation {
1102 lod: $crate::levels::Verbosity::Max,
1103 target: module_path!(),
1104 module_path: module_path!(),
1105 file: file!(),
1106 line: line!(),
1107 };
1108 };
1109}
1110
1111/// Expansion of `#[span_fn]` with properties on an async function.
1112#[doc(hidden)]
1113#[macro_export]
1114macro_rules! span_fn_future {
1115 ($name:expr, $future:expr, $($props:tt)+) => {
1116 $crate::__props!(@m span [future $name, $future] [] [] [] [] [] $($props)+)
1117 };
1118}
1119
1120#[doc(hidden)]
1121#[macro_export]
1122macro_rules! __span_set_properties {
1123 ($props:ident $(($k:tt, $vk:ident, $v:tt))*) => {
1124 $($crate::__span_set_property!($props $k $vk $v);)*
1125 };
1126}
1127
1128#[doc(hidden)]
1129#[macro_export]
1130macro_rules! __span_set_property {
1131 ($props:ident $k:tt disp $v:tt) => {
1132 $props.set_property($crate::__prop_key!(span $k), &$v)
1133 };
1134 ($props:ident $k:tt dbg $v:tt) => {
1135 $props.set_property($crate::__prop_key!(span $k), ::std::format_args!("{:?}", $v))
1136 };
1137 ($props:ident $k:tt bare $v:tt) => {
1138 $props.set_property(
1139 $crate::__prop_key!(span $k),
1140 &*$crate::property_value::PropertyValue::property_value(&$v),
1141 )
1142 };
1143}
1144
1145/// Interns the literal properties of a callsite on its first execution.
1146#[doc(hidden)]
1147#[macro_export]
1148macro_rules! __callsite_set {
1149 ($kind:ident $(($k:tt, lit, ($($v:tt)*)))+) => {{
1150 static CELL: ::std::sync::OnceLock<&'static $crate::property_set::PropertySet> =
1151 ::std::sync::OnceLock::new();
1152 static PAIRS: &[(&str, &str)] = &[$(($crate::__prop_key!($kind $k), $($v)*)),+];
1153 $crate::property_set::callsite_set(&CELL, PAIRS)
1154 }};
1155}
1156
1157/// The set of a callsite with `static` values: the literals and static values over the spread
1158/// set (or the empty one), interned once per distinct tuple of values.
1159#[doc(hidden)]
1160#[macro_export]
1161macro_rules! __static_set {
1162 ($kind:ident [] $(($k:tt, $tag:ident, $v:tt))+) => {
1163 $crate::__static_set!(@get $kind $crate::property_set::PropertySet::empty(),
1164 $(($k, $tag, $v))+)
1165 };
1166 ($kind:ident [$set:expr] $(($k:tt, $tag:ident, $v:tt))+) => {
1167 $crate::__static_set!(@get $kind $set, $(($k, $tag, $v))+)
1168 };
1169 (@get $kind:ident $base:expr, $(($k:tt, $tag:ident, $v:tt))+) => {{
1170 static CACHE: $crate::static_set_cache::StaticSetCache<{ [$(stringify!($k)),+].len() }> =
1171 $crate::static_set_cache::StaticSetCache::new();
1172 CACHE.get(
1173 $base,
1174 [$(($crate::__prop_key!($kind $k), $crate::__static_value!($tag $v))),+],
1175 )
1176 }};
1177}
1178
1179#[doc(hidden)]
1180#[macro_export]
1181macro_rules! __static_value {
1182 (lit ($($v:tt)*)) => {
1183 $($v)*
1184 };
1185 (stat ($($v:tt)*)) => {
1186 $crate::property_set::static_value($($v)*)
1187 };
1188}
1189
1190// The temporaries created for `bare`, `disp` and `dbg` values live until the end of the
1191// statement that makes the dispatch call, which is what lets the slice borrow them.
1192#[doc(hidden)]
1193#[macro_export]
1194macro_rules! __dyn_slice {
1195 ($kind:ident $(($k:tt, $vk:ident, $v:tt))*) => {
1196 &[$($crate::__dyn_prop!($kind $k $vk $v)),*]
1197 };
1198 // `extra` goes last, where `merge_properties` lets it win over a same-named entry.
1199 ($kind:ident $(($k:tt, $vk:ident, $v:tt))* ; $($extra:expr),+) => {
1200 &[$($crate::__dyn_prop!($kind $k $vk $v),)* $($extra),+]
1201 };
1202}
1203
1204#[doc(hidden)]
1205#[macro_export]
1206macro_rules! __dyn_prop {
1207 ($kind:ident $k:tt lit $v:tt) => {
1208 $crate::property_set::DynProperty::new($crate::__prop_key!($kind $k), $v)
1209 };
1210 ($kind:ident $k:tt bare $v:tt) => {
1211 $crate::property_set::DynProperty::new(
1212 $crate::__prop_key!($kind $k),
1213 &*$crate::property_value::PropertyValue::property_value(&$v),
1214 )
1215 };
1216 ($kind:ident $k:tt disp $v:tt) => {
1217 $crate::property_set::DynProperty::new(
1218 $crate::__prop_key!($kind $k),
1219 &*::std::format!("{}", $v),
1220 )
1221 };
1222 ($kind:ident $k:tt dbg $v:tt) => {
1223 $crate::property_set::DynProperty::new(
1224 $crate::__prop_key!($kind $k),
1225 &*::std::format!("{:?}", $v),
1226 )
1227 };
1228}
1229
1230/// Turns a property key into a `&'static str`. Analytics treats some names as column
1231/// overrides, so the macros reject them; a `..set` spread or a runtime `DynProperty` slice is
1232/// the way to set them (the `_dyn` metric macros set `name` and `unit` themselves).
1233#[doc(hidden)]
1234#[macro_export]
1235macro_rules! __prop_key {
1236 (log level) => {
1237 compile_error!(
1238 "`level` is reserved: the level is chosen by the macro (`info!`, `log!(Level::..)`)"
1239 )
1240 };
1241 (log "level") => {
1242 compile_error!(
1243 "`level` is reserved: the level is chosen by the macro (`info!`, `log!(Level::..)`)"
1244 )
1245 };
1246 (log target) => {
1247 compile_error!("`target` is reserved: pass it as `target: ..` before the other arguments")
1248 };
1249 (log "target") => {
1250 compile_error!("`target` is reserved: pass it as `target: ..` before the other arguments")
1251 };
1252 (metric target) => {
1253 compile_error!("`target` is reserved: pass it as `target: ..` before the metric name")
1254 };
1255 (metric "target") => {
1256 compile_error!("`target` is reserved: pass it as `target: ..` before the metric name")
1257 };
1258 (metric name) => {
1259 compile_error!("`name` is reserved: it is the first argument of the metric")
1260 };
1261 (metric "name") => {
1262 compile_error!("`name` is reserved: it is the first argument of the metric")
1263 };
1264 (metric unit) => {
1265 compile_error!("`unit` is reserved: it is the second argument of the metric")
1266 };
1267 (metric "unit") => {
1268 compile_error!("`unit` is reserved: it is the second argument of the metric")
1269 };
1270 (span name) => {
1271 compile_error!("`name` is reserved: it is the span's name")
1272 };
1273 (span "name") => {
1274 compile_error!("`name` is reserved: it is the span's name")
1275 };
1276 ($kind:ident $k:ident) => {
1277 stringify!($k)
1278 };
1279 ($kind:ident $k:literal) => {
1280 $k
1281 };
1282 ($kind:ident $($k:tt)*) => {
1283 compile_error!("a property key must be an identifier or a string literal")
1284 };
1285}
1286
1287/// Logs a message at the error level.
1288///
1289/// # Examples
1290///
1291/// ```
1292/// use micromegas_tracing::prelude::*;
1293///
1294/// # fn main() {
1295/// let (err_info, port) = ("No connection", 22);
1296///
1297/// error!("Error: {} on port {}", err_info, port);
1298/// error!(target: "app_events", "App Error: {}, Port: {}", err_info, 22);
1299/// # }
1300/// ```
1301#[macro_export]
1302macro_rules! error {
1303 (target: $target:expr, $($arg:tt)+) => (
1304 $crate::log!(target: $target, $crate::levels::Level::Error, $($arg)+)
1305 );
1306 ($($arg:tt)+) => (
1307 $crate::log!($crate::levels::Level::Error, $($arg)+)
1308 )
1309}
1310
1311/// Logs a message representing a crash or panic
1312#[macro_export]
1313macro_rules! fatal {
1314 (target: $target:expr, $($arg:tt)+) => (
1315 $crate::log!(target: $target, $crate::levels::Level::Fatal, $($arg)+)
1316 );
1317 ($($arg:tt)+) => (
1318 $crate::log!($crate::levels::Level::Fatal, $($arg)+)
1319 )
1320}
1321
1322/// Logs a message at the warn level.
1323///
1324/// # Examples
1325///
1326/// ```
1327/// use micromegas_tracing::prelude::*;
1328///
1329/// # fn main() {
1330/// let warn_description = "Invalid Input";
1331///
1332/// warn!("Warning! {}!", warn_description);
1333/// warn!(target: "input_events", "App received warning: {}", warn_description);
1334/// # }
1335/// ```
1336#[macro_export]
1337macro_rules! warn {
1338 (target: $target:expr, $($arg:tt)+) => (
1339 $crate::log!(target: $target, $crate::levels::Level::Warn, $($arg)+)
1340 );
1341 ($($arg:tt)+) => (
1342 $crate::log!($crate::levels::Level::Warn, $($arg)+)
1343 )
1344}
1345
1346/// Logs a message at the info level.
1347///
1348/// # Examples
1349///
1350/// ```
1351/// use micromegas_tracing::prelude::*;
1352///
1353/// # fn main() {
1354/// # struct Connection { port: u32, speed: f32 }
1355/// let conn_info = Connection { port: 40, speed: 3.20 };
1356///
1357/// info!("Connected to port {} at {} Mb/s", conn_info.port, conn_info.speed);
1358/// info!(target: "connection_events", "Successfull connection, port: {}, speed: {}",
1359/// conn_info.port, conn_info.speed);
1360/// # }
1361/// ```
1362#[macro_export]
1363macro_rules! info {
1364 (target: $target:expr, $($arg:tt)+) => (
1365 $crate::log!(target: $target, $crate::levels::Level::Info, $($arg)+)
1366 );
1367 ($($arg:tt)+) => (
1368 $crate::log!($crate::levels::Level::Info, $($arg)+)
1369 )
1370}
1371
1372/// Logs a message at the debug level.
1373///
1374/// # Examples
1375///
1376/// ```
1377/// use micromegas_tracing::debug;
1378///
1379/// # fn main() {
1380/// # struct Position { x: f32, y: f32 }
1381/// let pos = Position { x: 3.234, y: -1.223 };
1382///
1383/// debug!("New position: x: {}, y: {}", pos.x, pos.y);
1384/// debug!(target: "app_events", "New position: x: {}, y: {}", pos.x, pos.y);
1385/// # }
1386/// ```
1387#[macro_export]
1388macro_rules! debug {
1389 (target: $target:expr, $($arg:tt)+) => (
1390 $crate::log!(target: $target, $crate::levels::Level::Debug, $($arg)+)
1391 );
1392 ($($arg:tt)+) => (
1393 $crate::log!($crate::levels::Level::Debug, $($arg)+)
1394 )
1395}
1396
1397/// Logs a message at the trace level.
1398///
1399/// # Examples
1400///
1401/// ```
1402/// use micromegas_tracing::trace;
1403///
1404/// # fn main() {
1405/// # struct Position { x: f32, y: f32 }
1406/// let pos = Position { x: 3.234, y: -1.223 };
1407///
1408/// trace!("Position is: x: {}, y: {}", pos.x, pos.y);
1409/// trace!(target: "app_events", "x is {} and y is {}",
1410/// if pos.x >= 0.0 { "positive" } else { "negative" },
1411/// if pos.y >= 0.0 { "positive" } else { "negative" });
1412/// # }
1413/// ```
1414#[macro_export]
1415macro_rules! trace {
1416 (target: $target:expr, $($arg:tt)+) => (
1417 $crate::log!(target: $target, $crate::levels::Level::Trace, $($arg)+)
1418 );
1419 ($($arg:tt)+) => (
1420 $crate::log!($crate::levels::Level::Trace, $($arg)+)
1421 )
1422}
1423
1424/// Determines if a message logged at the specified level in that module will
1425/// be logged.
1426///
1427/// This can be used to avoid expensive computation of log message arguments if
1428/// the message would be ignored anyway.
1429///
1430/// # Examples
1431///
1432/// ```
1433/// use micromegas_tracing::prelude::*;
1434///
1435/// # fn foo() {
1436/// if log_enabled!(Level::Debug) {
1437/// let data = expensive_call();
1438/// debug!("expensive debug data: {} {}", data.x, data.y);
1439/// }
1440/// if log_enabled!(target: "Global", Level::Debug) {
1441/// let data = expensive_call();
1442/// debug!(target: "Global", "expensive debug data: {} {}", data.x, data.y);
1443/// }
1444/// # }
1445/// # struct Data { x: u32, y: u32 }
1446/// # fn expensive_call() -> Data { Data { x: 0, y: 0 } }
1447/// # fn main() {}
1448/// ```
1449#[macro_export(local_inner_macros)]
1450macro_rules! log_enabled {
1451 (target: $target:expr, $lvl:expr) => {{
1452 let lvl = $lvl;
1453 static LOG_ENABLED_METADATA: $crate::logs::LogMetadata = $crate::logs::LogMetadata {
1454 level: $lvl,
1455 level_filter: std::sync::atomic::AtomicU32::new($crate::logs::FILTER_LEVEL_UNSET_VALUE),
1456 fmt_str: "",
1457 target: $target,
1458 module_path: $crate::__log_module_path!(),
1459 file: $crate::__log_file!(),
1460 line: $crate::__log_line!(),
1461 };
1462 lvl <= $crate::levels::STATIC_MAX_LEVEL
1463 && lvl <= $crate::levels::max_level()
1464 && $crate::dispatch::log_enabled(&LOG_ENABLED_METADATA)
1465 }};
1466 ($lvl:expr) => {
1467 $crate::log_enabled!(target: $crate::__log_module_path!(), $lvl)
1468 };
1469}
1470
1471//pub const fn type_name_of<T>(_: &T) -> &'static str {
1472// //until type_name_of_val is out of nightly-only
1473// std::any::type_name::<T>()
1474//}
1475
1476#[doc(hidden)]
1477#[macro_export]
1478macro_rules! __function_name {
1479 () => {{
1480 // Okay, this is ugly, I get it. However, this is the best we can get on a stable rust.
1481 fn f() {}
1482 fn type_name_of<T>(_: T) -> &'static str {
1483 std::any::type_name::<T>()
1484 }
1485 let name = type_name_of(f);
1486 // `3` is the length of the `::f`.
1487 &name[..name.len() - 3]
1488 }};
1489}
1490
1491#[doc(hidden)]
1492#[macro_export]
1493macro_rules! __first_arg {
1494 ($first:tt) => {
1495 $first
1496 };
1497 ($first:tt, $($args:tt)*) => {
1498 $crate::__first_arg!($first)
1499 };
1500}
1501
1502#[doc(hidden)]
1503#[macro_export]
1504macro_rules! __log_format_args {
1505 ($($args:tt)*) => {
1506 format_args!($($args)*)
1507 };
1508}
1509
1510#[doc(hidden)]
1511#[macro_export]
1512macro_rules! __log_module_path {
1513 () => {
1514 module_path!()
1515 };
1516}
1517
1518#[doc(hidden)]
1519#[macro_export]
1520macro_rules! __log_file {
1521 () => {
1522 file!()
1523 };
1524}
1525
1526#[doc(hidden)]
1527#[macro_export]
1528macro_rules! __log_line {
1529 () => {
1530 line!()
1531 };
1532}