delog 0.1.8

Deferred logging, an implementation and extension of Rust's standard logging facade.
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
643
644
645
646
647
648
649
650
651
652
653
use core::sync::atomic::Ordering;
use core::{cmp, ptr};

#[cfg(not(feature = "portable-atomic"))]
use core::sync::atomic::AtomicUsize;
#[cfg(feature = "portable-atomic")]
use portable_atomic::AtomicUsize;

/// Semi-abstract characterization of the deferred loggers that the `delog!` macro produces.
///
/// # Safety
/// This trait is markes "unsafe" to signal that users should never (need to) "write their own",
/// but always go through the `delog!` macro.
///
/// The user has access to the global logger via `delog::logger()`, but only as TryLog/Log
/// implementation, not with this direct access to implementation details.
pub unsafe trait Delogger: log::Log + crate::TryLog + State<&'static AtomicUsize> {
    /// the underlying buffer
    fn buffer(&self) -> &'static mut [u8];
    /// How many characters were claimed so far.
    fn claimed(&self) -> &'static AtomicUsize;
    /// Call the flusher.
    fn flush(&self, logs: &str);
    /// Actually render the arguments (via internal static buffer).
    fn render(&self, record: &log::Record) -> &'static [u8];

    /// Capacity of circular buffer.
    fn capacity(&self) -> usize {
        self.buffer().len()
    }
}

/// Trait for either state or statistics of loggers.
pub trait State<T> {
    /// How often was one of the logging macros called.
    fn attempts(&self) -> T;
    /// How often was one of the logging macros called without early exit (e.g., buffer not full)
    fn successes(&self) -> T;
    /// How often was the flusher called.
    fn flushes(&self) -> T;
    /// How many bytes were flushed so far.
    fn read(&self) -> T;
    /// How many bytes were logged so far.
    fn written(&self) -> T;
}

#[derive(Clone, Copy, Debug)]
/// Statistics on logger usage.
pub struct Statistics {
    /// How often was one of the logging macros called.
    pub attempts: usize,
    /// How often was one of the logging macros called without early exit (e.g., buffer not full)
    pub successes: usize,
    /// How often was the flusher called.
    pub flushes: usize,
    /// How many bytes were flushed so far.
    pub read: usize,
    /// How many bytes were logged so far.
    pub written: usize,
}

/// Fallible, panic-free version of the `log::Log` trait.
///
/// The intention is actually that implementors of this trait also
/// implement `log::Log` in a panic-free fashion, and simply drop logs
/// that can't be logged. Because, if the user can handle the error, they
/// would be using the fallible macros, and if not, they most likely do **not**
/// want to crash.
pub trait TryLog: log::Log {
    /// Fallible logging call (fails when buffer is full)
    fn try_log(&self, _: &log::Record) -> core::result::Result<(), ()>;
}

/// TryLog with some usage statistics on top.
pub trait TryLogWithStatistics: TryLog + State<usize> {
    /// Read out statistics on logger usage.
    fn statistics(&self) -> Statistics {
        Statistics {
            attempts: self.attempts(),
            successes: self.successes(),
            flushes: self.flushes(),
            read: self.read(),
            written: self.written(),
        }
    }

    // /// How often was one of the logging macros called.
    // fn attempts(&self) -> usize;
    // /// How often was one of the logging macros called without early exit (e.g., buffer not full)
    // fn successes(&self) -> usize;
    // /// How often was the flusher called.
    // fn flushes(&self) -> usize;
    // /// How many bytes were flushed so far.
    // fn read(&self) -> usize;
    // /// How many bytes were logged so far.
    // fn written(&self) -> usize;
}

/// Generate a deferred logger with specified capacity and flushing mechanism.
///
/// Note that only the final "runner" generates, initializes and flushes such a deferred logger.
///
/// Libraries simply make calls to `log::log!`, or its drop-in replacement `delog::log!`,
/// and/or its extension `delog::log_now!`, and/or its alternatives `delog::try_log!` and  `delog::try_log_now`,
/// and/or the local logging variants `local_log!`.
#[cfg(not(any(
    feature = "max_level_off",
    all(not(debug_assertions), feature = "release_max_level_off")
)))]
#[macro_export]
macro_rules! delog {
    ($logger:ident, $capacity:expr, $render_capacity:expr, $flusher:ty) => {
        delog!(
            $logger,
            $capacity,
            $render_capacity,
            $flusher,
            renderer: $crate::render::DefaultRenderer
        );

        impl $logger {
            #[inline]
            pub fn init_default(
                level: $crate::log::LevelFilter,
                flusher: &'static $flusher,
            ) -> Result<(), ()> {
                $logger::init(level, flusher, $crate::render::default())
            }
        }
    };

    ($logger:ident, $capacity:expr, $flusher:ty) => {
        delog!(
            $logger,
            $capacity,
            $capacity,
            $flusher,
            renderer: $crate::render::DefaultRenderer
        );

        impl $logger {
            #[inline]
            pub fn init_default(
                level: $crate::log::LevelFilter,
                flusher: &'static $flusher,
            ) -> Result<(), ()> {
                $logger::init(level, flusher, $crate::render::default())
            }
        }
    };

    ($logger:ident, $capacity:expr, $flusher:ty, renderer: $renderer:ty) => {
        $crate::delog!($logger, $capacity, $capacity, $flusher, renderer: $renderer);
    };

    ($logger:ident, $capacity:expr, $render_capacity:expr, $flusher:ty, renderer: $renderer:ty) => {
        #[derive(Clone, Copy)]
        /// Generated deferred logging implementation.
        pub struct $logger {
            flusher: &'static $flusher,
            renderer: &'static $renderer,
            // immediate_flusher: &'static $flusher,
        }

        // log::Log implementations are required to be Send + Sync
        unsafe impl Send for $logger {}
        unsafe impl Sync for $logger {}

        impl $crate::log::Log for $logger {
            /// log level is set via log::set_max_level, not here, hence always true
            fn enabled(&self, _: &$crate::log::Metadata) -> bool {
                true
            }

            /// reads out logs from circular buffer, and flushes via injected flusher
            fn flush(&self) {
                let mut buf = [0u8; $capacity];

                let logs: &str = unsafe { $crate::dequeue(*self, &mut buf) };

                if logs.len() > 0 {
                    use $crate::Flusher;
                    self.flusher.flush(logs);
                }
            }

            fn log(&self, record: &$crate::log::Record) {
                // use $crate::Delogger;
                unsafe { $crate::enqueue(*self, record) }
            }
        }

        impl $crate::TryLog for $logger {
            fn try_log(&self, record: &$crate::log::Record) -> core::result::Result<(), ()> {
                unsafe { $crate::try_enqueue(*self, record) }
            }
        }

        impl $crate::State<usize> for $logger {
            fn attempts(&self) -> usize {
                <dyn $crate::Delogger>::attempts(self).load(core::sync::atomic::Ordering::SeqCst)
            }
            fn successes(&self) -> usize {
                <dyn $crate::Delogger>::successes(self).load(core::sync::atomic::Ordering::SeqCst)
            }

            fn flushes(&self) -> usize {
                <dyn $crate::Delogger>::flushes(self).load(core::sync::atomic::Ordering::SeqCst)
            }

            fn read(&self) -> usize {
                <dyn $crate::Delogger>::read(self).load(core::sync::atomic::Ordering::SeqCst)
            }
            fn written(&self) -> usize {
                <dyn $crate::Delogger>::written(self).load(core::sync::atomic::Ordering::SeqCst)
            }
        }

        impl $crate::TryLogWithStatistics for $logger {}

        #[allow(missing_docs)]
        impl $logger {
            #[inline]
            pub fn init(
                level: $crate::log::LevelFilter,
                flusher: &'static $flusher,
                renderer: &'static $renderer,
            ) -> Result<(), ()> {
                use core::sync::atomic::{AtomicBool, Ordering};

                static INITIALIZED: AtomicBool = AtomicBool::new(false);
                if INITIALIZED
                    .compare_exchange_weak(false, true, Ordering::AcqRel, Ordering::Acquire)
                    .is_ok()
                {
                    // let logger = Self { flusher, immediate_flusher: flusher };
                    let logger = Self { flusher, renderer };
                    Self::get().replace(logger);
                    $crate::logger().replace(Self::get().as_ref().unwrap());
                    $crate::log::set_logger(Self::get().as_ref().unwrap())
                        .map(|()| $crate::log::set_max_level(level))
                        .map_err(|_| ())
                } else {
                    Err(())
                }
            }

            fn get() -> &'static mut Option<$logger> {
                static mut LOGGER: Option<$logger> = None;
                unsafe { &mut LOGGER }
            }

            pub fn flush() {
                // gracefully degrade if we're not initialized yet
                if let Some(logger) = Self::get() {
                    $crate::log::Log::flush(logger)
                }
            }
        }

        impl $crate::State<&'static core::sync::atomic::AtomicUsize> for $logger {
            fn attempts(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static LOG_ATTEMPT_COUNT: AtomicUsize = AtomicUsize::new(0);
                &LOG_ATTEMPT_COUNT
            }

            fn successes(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static LOG_SUCCESS_COUNT: AtomicUsize = AtomicUsize::new(0);
                &LOG_SUCCESS_COUNT
            }

            fn flushes(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static LOG_FLUSH_COUNT: AtomicUsize = AtomicUsize::new(0);
                &LOG_FLUSH_COUNT
            }

            fn read(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static READ: AtomicUsize = AtomicUsize::new(0);
                &READ
            }

            fn written(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static WRITTEN: AtomicUsize = AtomicUsize::new(0);
                &WRITTEN
            }
        }

        unsafe impl $crate::Delogger for $logger {
            fn buffer(&self) -> &'static mut [u8] {
                static mut BUFFER: [u8; $capacity] = [0u8; $capacity];
                unsafe { &mut BUFFER }
            }

            fn flush(&self, logs: &str) {
                use $crate::Flusher;
                self.flusher.flush(logs)
            }

            fn claimed(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static CLAIMED: AtomicUsize = AtomicUsize::new(0);
                &CLAIMED
            }

            fn render(&self, record: &$crate::Record) -> &'static [u8] {
                static mut LOCAL_BUFFER: [u8; $render_capacity] = [0u8; $render_capacity];

                let local_buffer = unsafe { &mut LOCAL_BUFFER };
                use $crate::Renderer;
                self.renderer.render(local_buffer, record)
            }
        }
    };
}

/// Generate a deferred logger that will completely optimize out.
///
/// Note that the cfg-gate needs to be around the entire macro, as the library
/// calling it will not be the crate that has the `max_level_off` feature.
#[cfg(any(
    feature = "max_level_off",
    all(not(debug_assertions), feature = "release_max_level_off")
))]
#[macro_export]
macro_rules! delog {
    ($logger:ident, $capacity:expr, $flusher:ty) => {
        delog!(
            $logger,
            $capacity,
            $flusher,
            renderer: $crate::render::DefaultRenderer
        );

        impl $logger {
            #[inline]
            pub fn init_default(
                level: $crate::log::LevelFilter,
                flusher: &'static $flusher,
            ) -> Result<(), ()> {
                Ok(())
            }
        }
    };

    ($logger:ident, $capacity:expr, $flusher:ty, renderer: $renderer:ty) => {
        #[derive(Clone, Copy)]
        /// Generated deferred logging implementation.
        pub struct $logger {}

        // log::Log implementations are required to be Send + Sync
        unsafe impl Send for $logger {}
        unsafe impl Sync for $logger {}

        impl $crate::log::Log for $logger {
            /// log level is set via log::set_max_level, not here, hence always true
            fn enabled(&self, _: &$crate::log::Metadata) -> bool {
                true
            }

            /// reads out logs from circular buffer, and flushes via injected flusher
            fn flush(&self) {}

            fn log(&self, _record: &$crate::log::Record) {}
        }

        impl $crate::TryLog for $logger {
            fn try_log(&self, record: &$crate::log::Record) -> core::result::Result<(), ()> {
                Ok(())
            }
        }

        impl $crate::State<usize> for $logger {
            fn attempts(&self) -> usize {
                0
            }
            fn successes(&self) -> usize {
                0
            }
            fn flushes(&self) -> usize {
                0
            }
            fn read(&self) -> usize {
                0
            }
            fn written(&self) -> usize {
                0
            }
        }

        impl $crate::TryLogWithStatistics for $logger {}

        #[allow(missing_docs)]
        impl $logger {
            #[inline]
            pub fn init(
                level: $crate::log::LevelFilter,
                flusher: &'static $flusher,
                renderer: &'static $renderer,
            ) -> Result<(), ()> {
                Ok(())
            }

            fn get() -> &'static mut Option<$logger> {
                static mut LOGGER: Option<$logger> = None;
                unsafe { &mut LOGGER }
            }

            pub fn flush() {}
        }

        impl $crate::State<&'static core::sync::atomic::AtomicUsize> for $logger {
            fn attempts(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static LOG_ATTEMPT_COUNT: AtomicUsize = AtomicUsize::new(0);
                &LOG_ATTEMPT_COUNT
            }

            fn successes(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static LOG_SUCCESS_COUNT: AtomicUsize = AtomicUsize::new(0);
                &LOG_SUCCESS_COUNT
            }

            fn flushes(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static LOG_FLUSH_COUNT: AtomicUsize = AtomicUsize::new(0);
                &LOG_FLUSH_COUNT
            }

            fn read(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static READ: AtomicUsize = AtomicUsize::new(0);
                &READ
            }

            fn written(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static WRITTEN: AtomicUsize = AtomicUsize::new(0);
                &WRITTEN
            }
        }

        unsafe impl $crate::Delogger for $logger {
            fn buffer(&self) -> &'static mut [u8] {
                unsafe { &mut [] }
            }

            fn flush(&self, logs: &str) {}

            fn claimed(&self) -> &'static core::sync::atomic::AtomicUsize {
                use core::sync::atomic::AtomicUsize;
                static CLAIMED: AtomicUsize = AtomicUsize::new(0);
                &CLAIMED
            }

            fn render(&self, record: &$crate::Record) -> &'static [u8] {
                &[]
            }
        }
    };
}

/// The core "write to circular buffer" method. Marked unsafe to discourage use!
///
/// # Safety
/// Unfortunately exposed for all to see, as the `delog!` macro needs access to it to
/// implement the logger at call site. Hence marked as unsafe.
pub unsafe fn enqueue(delogger: impl Delogger, record: &log::Record) {
    crate::logger::try_enqueue(delogger, record).ok();
}

/// The fallible "write to circular buffer" method. Marked unsafe to discourage use!
///
/// # Safety
/// Unfortunately exposed for all to see, as the `delog!` macro needs access to it to
/// implement the logger at call site. Hence marked as unsafe.
///
/// This implementation needs some HEAVY testing. It is unsound on PC, where the OS
/// can schedule threads in any manner, but assumed to be sound in ARM Cortex-M NVIC
/// situations, where interrupts are "nested", in the sense that one may be interrupted,
/// then the interrupter can, ..., then the interrupter hands back control, ..., and finally
/// the original caller of this function regains control.
///
/// In this situation, we keep track of three counters `(read, written, claimed)`, with
/// invariants `read <= written <= claimed`. Each writer pessimistically gauges sufficient
/// capacity for its log by checking `claimed + size <= read + capacity`, accounting for the
/// wraparound. If so, the writer **atomically advances the claim counter**, and starts copying
/// its data in this newly claimed space. At the end, it is the duty of the "first" caller
/// to advance the `written` counter to the correct state.
#[allow(unused_unsafe, unused_variables)]
pub unsafe fn try_enqueue(
    delogger: impl Delogger,
    record: &log::Record,
) -> core::result::Result<(), ()> {
    #[cfg(any(
        feature = "max_level_off",
        all(not(debug_assertions), feature = "release_max_level_off")
    ))]
    {
        return Ok(());
    }
    #[cfg(not(any(
        feature = "max_level_off",
        all(not(debug_assertions), feature = "release_max_level_off")
    )))]
    {
        if record.level() > crate::log::max_level() {
            return Ok(());
        }

        // keep track of how man logs were attempted
        delogger.attempts().fetch_add(1, Ordering::SeqCst);

        if record.target() == "!" {
            // todo: possibly use separate immediate_flusher
            let input = delogger.render(record);
            let input = unsafe { core::str::from_utf8_unchecked(input) };
            Delogger::flush(&delogger, input);
            delogger.successes().fetch_add(1, Ordering::SeqCst);
            return Ok(());
        }

        let capacity = delogger.capacity();
        let log = delogger.render(record);
        let size = log.len();

        let previously_claimed = loop {
            let read = delogger.read().load(Ordering::SeqCst);
            let claimed = delogger.claimed().load(Ordering::SeqCst);

            // figure out the corner cases for "wrap-around" at usize capacity
            if claimed + size > read + capacity {
                // not enough space, currently
                return Err(());
            }

            // try to stake out our claim
            let previous = delogger.claimed().compare_exchange(
                claimed,
                claimed + size,
                Ordering::SeqCst,
                Ordering::SeqCst,
            );

            // we were not interrupted, the region is now ours
            if previous == Ok(claimed) {
                break claimed;
            }
        };

        // find out if we're the "first" and will need to update `written` at the end:
        let written = delogger.written().load(Ordering::SeqCst);
        let first: bool = written == previously_claimed;

        // now copy our data - we can be interrupted here at anytime
        let destination = previously_claimed % capacity;
        let buffer = delogger.buffer();
        if destination + size < capacity {
            // can do a single copy
            unsafe {
                ptr::copy_nonoverlapping(log.as_ptr(), buffer.as_mut_ptr().add(destination), size)
            };
        } else {
            // need to split
            let split = capacity - destination;
            unsafe {
                ptr::copy_nonoverlapping(log.as_ptr(), buffer.as_mut_ptr().add(destination), split);
                ptr::copy_nonoverlapping(
                    log.as_ptr().add(split),
                    buffer.as_mut_ptr(),
                    size - split,
                );
            }
        }

        if first {
            // update `written` to current `claimed` (which may be beyond our own claim)
            loop {
                let claimed = delogger.claimed().load(Ordering::SeqCst);
                delogger.written().store(claimed, Ordering::SeqCst);
                if claimed == delogger.claimed().load(Ordering::SeqCst) {
                    break;
                }
            }
        }

        delogger.successes().fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

/// The core "read from circular buffer" method. Marked unsafe to discourage use!
///
/// # Safety
/// Unfortunately exposed for all to see, as the `delog!` macro needs access to it to
/// implement the logger at call site. Hence marked as unsafe.
#[allow(unused_unsafe)]
pub unsafe fn dequeue(delogger: impl Delogger, buf: &mut [u8]) -> &str {
    delogger.flushes().fetch_add(1, Ordering::SeqCst);
    // we control the inputs, so we know this is a valid string
    unsafe { core::str::from_utf8_unchecked(drain_as_bytes(delogger, buf)) }
}

/// Copy out the contents of the `Logger` ring buffer into the given buffer,
/// updating `read` to make space for new log data
fn drain_as_bytes(delogger: impl Delogger, buf: &mut [u8]) -> &[u8] {
    unsafe {
        let read = delogger.read().load(Ordering::SeqCst);
        let written = delogger.written().load(Ordering::SeqCst);
        let p = delogger.buffer().as_ptr();

        // early exit to hint the compiler that `n` is not `0`
        let capacity = delogger.buffer().len();
        if capacity == 0 {
            return &[];
        }

        if written > read {
            // number of bytes to copy
            let available = cmp::min(buf.len(), written.wrapping_sub(read));

            let r = read % capacity;

            // NOTE `ptr::copy_nonoverlapping` instead of `copy_from_slice` to avoid panics
            if r + available > capacity {
                // two memcpy-s
                let mid = capacity - r;
                // buf[..mid].copy_from_slice(&buffer[r..]);
                ptr::copy_nonoverlapping(p.add(r), buf.as_mut_ptr(), mid);
                // buf[mid..mid + c].copy_from_slice(&buffer[..available - mid]);
                ptr::copy_nonoverlapping(p, buf.as_mut_ptr().add(mid), available - mid);
            } else {
                // single memcpy
                // buf[..c].copy_from_slice(&buffer[r..r + c]);
                ptr::copy_nonoverlapping(p.add(r), buf.as_mut_ptr(), available);
            }

            delogger
                .read()
                .store(read.wrapping_add(available), Ordering::SeqCst);

            // &buf[..c]
            buf.get_unchecked(..available)
        } else {
            &[]
        }
    }
}