emit 1.17.2

Developer-first diagnostics for Rust applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*!
The [`Setup`] type.

All functionality in `emit` is based on a [`crate::runtime::Runtime`]. When you call [`Setup::init`], it initializes the [`crate::runtime::shared`] runtime for you, which is also what macros use by default.

You can implement your own runtime, providing your own implementations of the ambient clock, randomness, and global context. First, disable the default features of `emit` in your `Cargo.toml`:

```toml
[dependencies.emit]
version = "1.17.2"
default-features = false
features = ["std"]
```

This will ensure the `rt` control parameter is always passed to macros so that your custom runtime will always be used.

You can define your runtime as a [`crate::runtime::AmbientSlot`] in a static and initialize it through [`Setup::init_slot`]:

```
// Define a static runtime to use
// In this example, we use the default implementations of most things,
// but you can also bring-your-own
static RUNTIME: emit::runtime::AmbientSlot = emit::runtime::AmbientSlot::new();

let rt = emit::setup()
    .emit_to(emit::emitter::from_fn(|evt| println!("{}", evt.msg())))
    .init_slot(&RUNTIME);

// Use your runtime with the `rt` control parameter
emit::emit!(rt: RUNTIME.get(), "emitted through a custom runtime");

rt.blocking_flush(std::time::Duration::from_secs(5));
```

```text
emitted through a custom runtime
```

The [`crate::runtime::AmbientSlot`] is type-erased, but you can also define your own fully concrete runtimes too:

```
// Define a static runtime to use
// In this example, we use the default implementations of most things,
// but you can also bring-your-own
static RUNTIME: emit::runtime::Runtime<
    MyEmitter,
    emit::Empty,
    emit::platform::DefaultCtxt,
    emit::platform::DefaultClock,
    emit::platform::DefaultRng,
> = emit::runtime::Runtime::build(
    MyEmitter,
    emit::Empty,
    emit::platform::DefaultCtxt::shared(),
    emit::platform::DefaultClock::new(),
    emit::platform::DefaultRng::new(),
);

struct MyEmitter;

impl emit::Emitter for MyEmitter {
    fn emit<E: emit::event::ToEvent>(&self, evt: E) {
        println!("{}", evt.to_event().msg());
    }

    fn blocking_flush(&self, _: std::time::Duration) -> bool {
        // Nothing to flush
        true
    }
}

// Use your runtime with the `rt` control parameter
emit::emit!(rt: &RUNTIME, "emitted through a custom runtime");
```

```text
emitted through a custom runtime
```
*/

use core::time::Duration;

use emit_core::{
    and::And,
    clock::Clock,
    ctxt::Ctxt,
    emitter::Emitter,
    filter::Filter,
    rng::Rng,
    runtime::{
        AmbientRuntime, AmbientSlot, InternalClock, InternalCtxt, InternalEmitter, InternalFilter,
        InternalRng, Runtime,
    },
};

/**
Configure `emit` with [`Emitter`]s, [`Filter`]s, and [`Ctxt`].

This function should be called as early in your application as possible. It returns a [`Setup`] builder that, once configured, can be initialized with a call to [`Setup::init`].
*/
pub fn setup() -> Setup {
    Setup::default()
}

pub use crate::platform::{DefaultClock, DefaultCtxt, DefaultEmitter, DefaultFilter, DefaultRng};

/**
A configuration builder for an `emit` runtime.
*/
#[must_use = "call `.init()` to finish setup"]
pub struct Setup<
    TEmitter = DefaultEmitter,
    TFilter = DefaultFilter,
    TCtxt = DefaultCtxt,
    TClock = DefaultClock,
    TRng = DefaultRng,
> {
    emitter: SetupCell<TEmitter>,
    filter: SetupCell<TFilter>,
    ctxt: SetupCell<TCtxt>,
    clock: SetupCell<TClock>,
    rng: SetupCell<TRng>,
}

struct SetupCell<T> {
    value: T,
    set: bool,
}

impl<T: Default> SetupCell<T> {
    fn initial() -> Self {
        SetupCell {
            value: Default::default(),
            set: false,
        }
    }
}

impl<T> SetupCell<T> {
    fn new(value: T) -> Self {
        SetupCell { value, set: true }
    }

    fn set<U>(self, set: impl FnOnce(T) -> U) -> SetupCell<U> {
        SetupCell {
            value: set(self.value),
            set: true,
        }
    }
}

impl Default for Setup {
    fn default() -> Self {
        Self::new()
    }
}

impl Setup {
    /**
    Create a new builder with the default [`Emitter`], [`Filter`], and [`Ctxt`].
    */
    pub fn new() -> Self {
        Setup {
            emitter: SetupCell::initial(),
            filter: SetupCell::initial(),
            ctxt: SetupCell::initial(),
            clock: SetupCell::initial(),
            rng: SetupCell::initial(),
        }
    }
}

impl<TEmitter: Emitter, TFilter: Filter, TCtxt: Ctxt, TClock: Clock, TRng: Rng>
    Setup<TEmitter, TFilter, TCtxt, TClock, TRng>
{
    /**
    Set the [`Emitter`] that will receive diagnostic events.
    */
    pub fn emit_to<UEmitter: Emitter>(
        self,
        emitter: UEmitter,
    ) -> Setup<UEmitter, TFilter, TCtxt, TClock, TRng> {
        Setup {
            emitter: SetupCell::new(emitter),
            filter: self.filter,
            ctxt: self.ctxt,
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Add an [`Emitter`] that will also receive diagnostic events.
    */
    pub fn and_emit_to<UEmitter: Emitter>(
        self,
        emitter: UEmitter,
    ) -> Setup<And<TEmitter, UEmitter>, TFilter, TCtxt, TClock, TRng> {
        Setup {
            emitter: self.emitter.set(|first| first.and_to(emitter)),
            filter: self.filter,
            ctxt: self.ctxt,
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Map the current [`Emitter`] into a new value.
    */
    pub fn map_emitter<UEmitter: Emitter>(
        self,
        map: impl FnOnce(TEmitter) -> UEmitter,
    ) -> Setup<UEmitter, TFilter, TCtxt, TClock, TRng> {
        Setup {
            emitter: self.emitter.set(map),
            filter: self.filter,
            ctxt: self.ctxt,
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Set the [`Filter`] that will be applied before diagnostic events are emitted.
    */
    pub fn emit_when<UFilter: Filter>(
        self,
        filter: UFilter,
    ) -> Setup<TEmitter, UFilter, TCtxt, TClock, TRng> {
        Setup {
            emitter: self.emitter,
            filter: SetupCell::new(filter),
            ctxt: self.ctxt,
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Add a [`Filter`] that will also be applied before diagnostic events are emitted.
    */
    pub fn and_emit_when<UFilter: Filter>(
        self,
        filter: UFilter,
    ) -> Setup<TEmitter, And<TFilter, UFilter>, TCtxt, TClock, TRng> {
        Setup {
            emitter: self.emitter,
            filter: self.filter.set(|first| first.and_when(filter)),
            ctxt: self.ctxt,
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Set the [`Ctxt`] that will store ambient properties and attach them to diagnostic events.
    */
    pub fn with_ctxt<UCtxt: Ctxt>(
        self,
        ctxt: UCtxt,
    ) -> Setup<TEmitter, TFilter, UCtxt, TClock, TRng> {
        Setup {
            emitter: self.emitter,
            filter: self.filter,
            ctxt: SetupCell::new(ctxt),
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Map the current [`Ctxt`] into a new value.
    */
    pub fn map_ctxt<UCtxt: Ctxt>(
        self,
        map: impl FnOnce(TCtxt) -> UCtxt,
    ) -> Setup<TEmitter, TFilter, UCtxt, TClock, TRng> {
        Setup {
            emitter: self.emitter,
            filter: self.filter,
            ctxt: self.ctxt.set(map),
            clock: self.clock,
            rng: self.rng,
        }
    }

    /**
    Set the [`Clock`] used to assign timestamps and run timers.
    */
    pub fn with_clock<UClock: Clock>(
        self,
        clock: UClock,
    ) -> Setup<TEmitter, TFilter, TCtxt, UClock, TRng> {
        Setup {
            emitter: self.emitter,
            filter: self.filter,
            ctxt: self.ctxt,
            clock: SetupCell::new(clock),
            rng: self.rng,
        }
    }

    /**
    Set the [`Rng`] used to assign trace and span ids.
    */
    pub fn with_rng<URng: Rng>(self, rng: URng) -> Setup<TEmitter, TFilter, TCtxt, TClock, URng> {
        Setup {
            emitter: self.emitter,
            filter: self.filter,
            ctxt: self.ctxt,
            clock: self.clock,
            rng: SetupCell::new(rng),
        }
    }

    /**
    Initialize a standalone runtime.
    */
    pub fn init_runtime(self) -> Runtime<TEmitter, TFilter, TCtxt, TClock, TRng> {
        let _ = (
            self.emitter.set,
            self.filter.set,
            self.ctxt.set,
            self.clock.set,
            self.rng.set,
        );

        Runtime::build(
            self.emitter.value,
            self.filter.value,
            self.ctxt.value,
            self.clock.value,
            self.rng.value,
        )
    }
}

impl<
        TEmitter: Emitter + Send + Sync + 'static,
        TFilter: Filter + Send + Sync + 'static,
        TCtxt: Ctxt + Send + Sync + 'static,
        TClock: Clock + Send + Sync + 'static,
        TRng: Rng + Send + Sync + 'static,
    > Setup<TEmitter, TFilter, TCtxt, TClock, TRng>
where
    TCtxt::Frame: Send + 'static,
{
    #[cfg(feature = "implicit_rt")]
    fn check_platform_is_initialized(&self) {
        let _ = (self.ctxt.set, self.clock.set, self.rng.set);

        #[cfg(feature = "implicit_internal_rt")]
        {
            use crate::Frame;
            use emit_core::{
                empty::Empty, event::Event, props::Props as _, runtime::internal_slot,
                template::Template,
            };

            if !self.emitter.set {
                internal_slot().get().emit(Event::new(
                    mdl!(),
                    Template::literal("an `Emitter` hasn't been configured; this means any emitted events will be discarded"),
                    Empty,
                    Empty,
                ));
            }

            if !self.ctxt.set {
                // Check whether the default context is able to track properties
                let tracks_props =
                    Frame::root(&self.ctxt.value, ("check_platform_is_initialized", true))
                        .with(|props| props.pull("check_platform_is_initialized").unwrap_or(false));

                if !tracks_props {
                    internal_slot().get().emit(Event::new(
                        mdl!(),
                        Template::literal("a `Ctxt` hasn't been configured and the default does not track properties; this means contextual logging will be unavailable"),
                        Empty,
                        Empty,
                    ));
                }
            }

            if !self.clock.set {
                // Check whether the default clock is able to tell time
                if self.clock.value.now().is_none() {
                    internal_slot().get().emit(Event::new(
                        mdl!(),
                        Template::literal("a `Clock` hasn't been configured and the default does not tell time; this means events will not include timestamps"),
                        Empty,
                        Empty,
                    ));
                }
            }

            if !self.rng.set {
                // Check whether the default rng is able to generate data
                if self.rng.value.fill([0; 1]).is_none() {
                    internal_slot().get().emit(Event::new(
                        mdl!(),
                        Template::literal("a `Rng` hasn't been configured and the default does not generate values; this means trace and span ids will not be generated"),
                        Empty,
                        Empty,
                    ));
                }
            }
        }
    }

    /**
    Initialize the default runtime used by `emit` macros.

    This method initializes [`crate::runtime::shared`].

    # Panics

    This method will panic if the slot has already been initialized.
    */
    #[must_use = "call `flush_on_drop` or call `blocking_flush` at the end of `main` to ensure events are flushed."]
    #[cfg(feature = "implicit_rt")]
    pub fn init(self) -> Init<'static, TEmitter, TCtxt> {
        self.check_platform_is_initialized();

        self.init_slot(emit_core::runtime::shared_slot())
    }

    /**
    Try initialize the default runtime used by `emit` macros.

    This method initializes [`crate::runtime::shared`].

    If the slot is already initialized, this method will return `None`.
    */
    #[must_use = "call `flush_on_drop` or call `blocking_flush` at the end of `main` to ensure events are flushed."]
    #[cfg(feature = "implicit_rt")]
    pub fn try_init(self) -> Option<Init<'static, TEmitter, TCtxt>> {
        self.check_platform_is_initialized();

        self.try_init_slot(emit_core::runtime::shared_slot())
    }

    /**
    Initialize a runtime in the given static `slot`.

    # Panics

    This method will panic if the slot has already been initialized.
    */
    #[must_use = "call `flush_on_drop` or call `blocking_flush` at the end of `main` to ensure events are flushed."]
    pub fn init_slot<'a>(self, slot: &'a AmbientSlot) -> Init<'a, TEmitter, TCtxt> {
        self.try_init_slot(slot).expect("already initialized")
    }

    /**
    Try initialize a runtime in the given static `slot`.

    If the slot is already initialized, this method will return `None`.
    */
    #[must_use = "call `flush_on_drop` or call `blocking_flush` at the end of `main` to ensure events are flushed."]
    pub fn try_init_slot<'a>(self, slot: &'a AmbientSlot) -> Option<Init<'a, TEmitter, TCtxt>> {
        let ambient = slot.init(
            Runtime::new()
                .with_emitter(self.emitter.value)
                .with_filter(self.filter.value)
                .with_ctxt(self.ctxt.value)
                .with_clock(self.clock.value)
                .with_rng(self.rng.value),
        )?;

        Some(Init {
            rt: slot.get(),
            emitter: *ambient.emitter(),
            ctxt: *ambient.ctxt(),
        })
    }
}

impl<
        TEmitter: InternalEmitter + Send + Sync + 'static,
        TFilter: InternalFilter + Send + Sync + 'static,
        TCtxt: InternalCtxt + Send + Sync + 'static,
        TClock: InternalClock + Send + Sync + 'static,
        TRng: InternalRng + Send + Sync + 'static,
    > Setup<TEmitter, TFilter, TCtxt, TClock, TRng>
where
    TCtxt::Frame: Send + 'static,
{
    /**
    Initialize the internal runtime used for diagnosing runtimes themselves.

    This method initializes [`crate::runtime::internal`].

    # Panics

    This method will panic if the slot has already been initialized.
    */
    #[must_use = "call `flush_on_drop` or call `blocking_flush` at the end of `main` (after flushing the main runtime) to ensure events are flushed."]
    #[cfg(feature = "implicit_internal_rt")]
    pub fn init_internal(self) -> Init<'static, TEmitter, TCtxt> {
        self.try_init_internal().expect("already initialized")
    }

    /**
    Initialize the internal runtime used for diagnosing runtimes themselves.

    This method initializes [`crate::runtime::internal`].

    If the slot is already initialized, this method will return `None`.
    */
    #[must_use = "call `flush_on_drop` or call `blocking_flush` at the end of `main` (after flushing the main runtime) to ensure events are flushed."]
    #[cfg(feature = "implicit_internal_rt")]
    pub fn try_init_internal(self) -> Option<Init<'static, TEmitter, TCtxt>> {
        let slot = emit_core::runtime::internal_slot();

        let ambient = slot.init(
            Runtime::new()
                .with_emitter(self.emitter.value)
                .with_filter(self.filter.value)
                .with_ctxt(self.ctxt.value)
                .with_clock(self.clock.value)
                .with_rng(self.rng.value),
        )?;

        Some(Init {
            rt: slot.get(),
            emitter: *ambient.emitter(),
            ctxt: *ambient.ctxt(),
        })
    }
}

/**
The result of calling [`Setup::init`].

This type is a handle to an initialized runtime that can be used to ensure it's fully flushed with a call to [`Init::blocking_flush`] before your application exits.
*/
pub struct Init<'a, TEmitter: Emitter + ?Sized = DefaultEmitter, TCtxt: Ctxt + ?Sized = DefaultCtxt>
{
    rt: &'a AmbientRuntime<'a>,
    emitter: &'a TEmitter,
    ctxt: &'a TCtxt,
}

impl<'a, TEmitter: Emitter + ?Sized, TCtxt: Ctxt + ?Sized> Init<'a, TEmitter, TCtxt> {
    /**
    Get a reference to the initialized [`Emitter`].
    */
    pub fn emitter(&self) -> &'a TEmitter {
        self.emitter
    }

    /**
    Get a reference to the initialized [`Ctxt`].
    */
    pub fn ctxt(&self) -> &'a TCtxt {
        self.ctxt
    }

    /**
    Get the underlying runtime that was initialized.
    */
    pub fn get(&self) -> &'a AmbientRuntime<'a> {
        self.rt
    }

    /**
    Flush the runtime, ensuring all diagnostic events are fully processed.

    This method forwards to [`Emitter::blocking_flush`], which has details on how the timeout is handled.
    */
    pub fn blocking_flush(&self, timeout: Duration) -> bool {
        self.emitter.blocking_flush(timeout)
    }

    /**
    Flush the runtime when the returned guard is dropped, ensuring all diagnostic events are fully processed.

    This method forwards to [`Emitter::blocking_flush`], which has details on how the timeout is handled.

    **Important:** Ensure you bind an identifier to this method, otherwise it will be immediately dropped instead of at the end of your `main`:

    ```
    # use std::time::Duration;
    fn main() {
        // Use an ident like `_guard`, not `_`
        let _guard = emit::setup().init().flush_on_drop(Duration::from_secs(5));

        // Your code goes here
    }
    ```
    */
    pub fn flush_on_drop(self, timeout: Duration) -> InitGuard<'a, TEmitter, TCtxt> {
        InitGuard {
            inner: self,
            timeout,
        }
    }
}

/**
The result of calling [`Init::flush_on_drop`].

This type is a guard that will call [`Init::blocking_flush`] when it goes out of scope. It helps ensure diagnostics are emitted, even if a panic unwinds through your `main` function.
*/
pub struct InitGuard<
    'a,
    TEmitter: Emitter + ?Sized = DefaultEmitter,
    TCtxt: Ctxt + ?Sized = DefaultCtxt,
> {
    inner: Init<'a, TEmitter, TCtxt>,
    timeout: Duration,
}

impl<'a, TEmitter: Emitter + ?Sized, TCtxt: Ctxt + ?Sized> InitGuard<'a, TEmitter, TCtxt> {
    /**
    Get the inner [`Init`] value, which can then be used to get the underlying [`AmbientRuntime`].
    */
    pub fn inner(&self) -> &Init<'a, TEmitter, TCtxt> {
        &self.inner
    }
}

impl<'a, TEmitter: Emitter + ?Sized, TCtxt: Ctxt + ?Sized> Drop for InitGuard<'a, TEmitter, TCtxt> {
    fn drop(&mut self) {
        self.inner.blocking_flush(self.timeout);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn try_init() {
        let slot = AmbientSlot::new();

        assert!(setup().try_init_slot(&slot).is_some());
        assert!(setup().try_init_slot(&slot).is_none());
    }
}