captains-log 0.15.4

A minimalist customizable logger for rust, based on the `log` crate, but also adapted to `tracing`, for production and testing scenario.
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
use crate::{buf_file_impl::LogSinkBufFile, console_impl::LogSinkConsole, file_impl::LogSinkFile};
use crate::{config::Builder, time::Timer};
use arc_swap::ArcSwap;
use backtrace::Backtrace;
use signal_hook::iterator::Signals;
use std::cell::UnsafeCell;
use std::io::Error;
use std::mem::transmute;
use std::sync::{
    atomic::{AtomicBool, AtomicU64, Ordering},
    Arc,
};
use std::thread;

#[cfg(feature = "tracing")]
use crate::tracing_bridge::{CaptainsLogLayer, TracingFormatter, TracingText};
#[cfg(feature = "tracing")]
use tracing::{dispatcher, Dispatch};
#[cfg(feature = "tracing")]
use tracing_subscriber::prelude::*;

#[enum_dispatch]
pub(crate) trait LogSinkTrait {
    fn open(&self) -> std::io::Result<()>;

    fn reopen(&self) -> std::io::Result<()>;

    fn log(&self, now: &Timer, r: &log::Record);

    fn flush(&self);
}

#[enum_dispatch(LogSinkTrait)]
pub enum LogSink {
    File(LogSinkFile),
    BufFile(LogSinkBufFile),
    Console(LogSinkConsole),
    #[cfg(feature = "syslog")]
    Syslog(crate::syslog::LogSinkSyslog),
    #[cfg(feature = "ringfile")]
    RingFile(crate::ringfile::LogSinkRingFile),
}

struct GlobalLoggerStatic {
    logger: UnsafeCell<GlobalLogger>,
    lock: AtomicBool,
    inited: AtomicBool,
}

struct GlobalLoggerGuard<'a>(&'a GlobalLoggerStatic);

impl Drop for GlobalLoggerGuard<'_> {
    fn drop(&mut self) {
        self.0.unlock();
    }
}

impl GlobalLoggerStatic {
    const fn new() -> Self {
        Self {
            logger: UnsafeCell::new(GlobalLogger {
                config_checksum: AtomicU64::new(0),
                inner: None,
                signal_listener: AtomicBool::new(false),
                #[cfg(feature = "tracing")]
                tracing_inited: AtomicBool::new(false),
            }),
            lock: AtomicBool::new(false),
            inited: AtomicBool::new(false),
        }
    }

    #[inline(always)]
    fn get_logger_mut(&self) -> &mut GlobalLogger {
        unsafe { transmute(self.logger.get()) }
    }

    /// Assume already setup, for internal use.
    #[inline(always)]
    fn get_logger(&'static self) -> &'static GlobalLogger {
        unsafe { transmute(self.logger.get()) }
    }

    /// This is the safe version for public use.
    #[inline(always)]
    fn try_get_logger(&'static self) -> Option<&'static GlobalLogger> {
        let logger = self.get_logger();
        if self.inited.load(Ordering::SeqCst) {
            return Some(logger);
        } else {
            None
        }
    }

    #[inline]
    fn lock<'a>(&'a self) -> GlobalLoggerGuard<'a> {
        while self
            .lock
            .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            // Normally this does not contend, if your test does not run concurrently.
            std::thread::yield_now();
        }
        GlobalLoggerGuard(self)
    }

    fn unlock(&self) {
        self.lock.store(false, Ordering::SeqCst);
    }

    /// Return Ok(false) when reinit, Ok(true) when first init, Err for error
    fn try_setup(&'static self, builder: &Builder) -> Result<bool, Error> {
        let _guard = self.lock();
        let res = { self.get_logger().check_the_same(builder) };
        match res {
            Some(true) => {
                // checksum is the same
                if let Err(e) = self.get_logger().open() {
                    eprintln!("failed to open log sink: {:?}", e);
                    return Err(e);
                }
                // reset the log level
                log::set_max_level(builder.get_max_level());
                return Ok(false);
            }
            Some(false) => {
                // checksum is not the same
                if !builder.dynamic {
                    let e = Error::other("log config differs but dynamic=false");
                    eprintln!("{:?}", e);
                    return Err(e);
                }
                let logger = self.get_logger();
                if let Err(e) = logger.reinit(builder) {
                    eprintln!("{:?}", e);
                    return Err(e);
                }
                // reset the log level
                log::set_max_level(builder.get_max_level());
                #[cfg(feature = "tracing")]
                {
                    if builder.tracing_global {
                        logger.init_tracing_global()?;
                    }
                }
                return Ok(false);
            }
            None => {
                // first init
                let res = { self.get_logger_mut().init(builder) };
                res?;
                #[cfg(feature = "tracing")]
                {
                    let logger = self.get_logger();
                    if builder.tracing_global {
                        logger.init_tracing_global()?;
                    }
                }
                self.inited.store(true, Ordering::SeqCst);
                return Ok(true);
            }
        }
    }
}

unsafe impl Send for GlobalLoggerStatic {}
unsafe impl Sync for GlobalLoggerStatic {}

/// Initialize global logger from Builder
///
/// **NOTE**: You can call this function multiple times when **builder.dynamic=true**,
/// but **cannot mixed used captains_log with other logger implement**, because log::set_logger()
/// cannot be called twice.
pub fn setup_log(builder: Builder) -> Result<&'static GlobalLogger, Error> {
    if GLOBAL_LOGGER.try_setup(&builder)? {
        let logger = GLOBAL_LOGGER.get_logger();
        // Set logger can only be called once
        if let Err(e) = log::set_logger(logger) {
            eprintln!("log::set_logger return error: {:?}", e);
            return Err(Error::other(format!("log::set_logger() failed: {:?}", e)));
        }
        log::set_max_level(builder.get_max_level());
        // panic hook can be set multiple times
        if builder.continue_when_panic {
            std::panic::set_hook(Box::new(panic_no_exit_hook));
        } else {
            std::panic::set_hook(Box::new(panic_and_exit_hook));
        }
        let signals = builder.rotation_signals.clone();
        if signals.len() > 0 {
            if false == logger.signal_listener.swap(true, Ordering::SeqCst) {
                thread::spawn(move || {
                    GLOBAL_LOGGER.get_logger().listener_for_signal(signals);
                });
            }
        }
        Ok(logger)
    } else {
        Ok(GLOBAL_LOGGER.get_logger())
    }
}

/// Return the GlobalLogger after initialized.
pub fn get_global_logger() -> Option<&'static GlobalLogger> {
    GLOBAL_LOGGER.try_get_logger()
}

/// Global static structure to hold the logger
pub struct GlobalLogger {
    /// checksum for config comparison
    config_checksum: AtomicU64,
    /// Global static needs initialization when declaring,
    /// default to be empty
    inner: Option<LoggerInner>,
    signal_listener: AtomicBool,
    #[cfg(feature = "tracing")]
    tracing_inited: AtomicBool,
}

enum LoggerInnerSink {
    Once(Vec<LogSink>),
    // using ArcSwap has more cost
    Dyn(ArcSwap<Vec<LogSink>>),
}

struct LoggerInner {
    sinks: LoggerInnerSink,
}

unsafe impl Send for LoggerInner {}
unsafe impl Sync for LoggerInner {}

impl LoggerInner {
    #[inline]
    fn new(dynamic: bool, sinks: Vec<LogSink>) -> Self {
        let sinks = if dynamic {
            LoggerInnerSink::Dyn(ArcSwap::new(Arc::new(sinks)))
        } else {
            LoggerInnerSink::Once(sinks)
        };
        Self { sinks }
    }

    #[inline]
    fn set(&self, sinks: Vec<LogSink>) -> std::io::Result<()> {
        match &self.sinks {
            LoggerInnerSink::Once(_) => {
                let e = Error::other("previous logger does not init with dynamic=true");
                return Err(e);
            }
            LoggerInnerSink::Dyn(d) => {
                d.store(Arc::new(sinks));
            }
        }
        Ok(())
    }
}

impl GlobalLogger {
    fn listener_for_signal(&self, signals: Vec<i32>) {
        println!("signal_listener started");
        let mut signals = Signals::new(&signals).unwrap();
        for __sig in signals.forever() {
            let _ = self.reopen();
        }
        println!("signal_listener exit");
    }

    /// On program/test Initialize
    fn open(&self) -> std::io::Result<()> {
        if let Some(inner) = self.inner.as_ref() {
            match &inner.sinks {
                LoggerInnerSink::Once(inner) => {
                    for sink in inner.iter() {
                        sink.open()?;
                    }
                }
                LoggerInnerSink::Dyn(inner) => {
                    let sinks = inner.load();
                    for sink in sinks.iter() {
                        sink.open()?;
                    }
                }
            }
        }
        println!("log sinks opened");
        Ok(())
    }

    /// Reopen file. This is a signal handler, also can be called manually.
    pub fn reopen(&self) -> std::io::Result<()> {
        if let Some(inner) = self.inner.as_ref() {
            match &inner.sinks {
                LoggerInnerSink::Once(inner) => {
                    for sink in inner.iter() {
                        sink.reopen()?;
                    }
                }
                LoggerInnerSink::Dyn(inner) => {
                    let sinks = inner.load();
                    for sink in sinks.iter() {
                        sink.reopen()?;
                    }
                }
            }
        }
        println!("log sinks re-opened");
        Ok(())
    }

    /// Return Some(true) to skip, Some(false) to reinit, None to init
    #[inline]
    fn check_the_same(&self, builder: &Builder) -> Option<bool> {
        if self.inner.is_some() {
            return Some(self.config_checksum.load(Ordering::Acquire) == builder.cal_checksum());
        }
        None
    }

    /// Re-configure the logger sink
    fn reinit(&self, builder: &Builder) -> std::io::Result<()> {
        let sinks = builder.build_sinks()?;
        if let Some(inner) = self.inner.as_ref() {
            inner.set(sinks)?;
            self.config_checksum.store(builder.cal_checksum(), Ordering::Release);
        } else {
            unreachable!();
        }
        Ok(())
    }

    fn init(&mut self, builder: &Builder) -> std::io::Result<()> {
        let sinks = builder.build_sinks()?;
        assert!(self.inner.is_none());
        self.inner.replace(LoggerInner::new(builder.dynamic, sinks));
        self.config_checksum.store(builder.cal_checksum(), Ordering::Release);
        Ok(())
    }

    #[cfg(feature = "tracing")]
    #[inline]
    fn init_tracing_global(&'static self) -> Result<(), Error> {
        let dist = self.tracing_dispatch::<TracingText>()?;
        if let Err(_) = dispatcher::set_global_default(dist) {
            let e = Error::other("tracing global dispatcher already exists");
            eprintln!("{:?}", e);
            return Err(e);
        }
        self.tracing_inited.store(true, Ordering::SeqCst);
        Ok(())
    }

    #[cfg(feature = "tracing")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tracing")))]
    /// Initialize a layer for tracing. Use this when you stacking multiple tracing layers.
    ///
    /// For usage, checkout the doc in [crate::tracing_bridge]
    ///
    /// # NOTE:
    ///
    /// In order to prevent duplicate output, it will fail if out tracing global subscriber
    /// has been initialized.
    pub fn tracing_layer<F: TracingFormatter>(
        &'static self,
    ) -> std::io::Result<CaptainsLogLayer<F>> {
        if self.tracing_inited.load(Ordering::SeqCst) {
            let e = Error::other("global tracing dispatcher exists");
            eprintln!("{:?}", e);
            return Err(e);
        }
        return Ok(CaptainsLogLayer::<F>::new(self));
    }

    #[cfg(feature = "tracing")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tracing")))]
    /// Initialize a tracing Dispatch, you can set_global_default() or use in a scope.
    ///
    /// For usage, checkout the doc in [crate::tracing_bridge]
    ///
    /// # NOTE:
    ///
    /// In order to prevent duplicate output, it will fail if out tracing global subscriber
    /// has been initialized.
    pub fn tracing_dispatch<F: TracingFormatter>(&'static self) -> std::io::Result<Dispatch> {
        if self.tracing_inited.load(Ordering::SeqCst) {
            let e = Error::other("global tracing dispatcher exists");
            eprintln!("{:?}", e);
            return Err(e);
        }
        return Ok(Dispatch::new(
            tracing_subscriber::registry().with(self.tracing_layer::<F>().unwrap()),
        ));
    }
}

impl log::Log for GlobalLogger {
    #[inline(always)]
    fn enabled(&self, _m: &log::Metadata) -> bool {
        true
    }

    #[inline(always)]
    fn log(&self, r: &log::Record) {
        let now = Timer::new();
        if let Some(inner) = self.inner.as_ref() {
            match &inner.sinks {
                LoggerInnerSink::Once(inner) => {
                    for sink in inner.iter() {
                        sink.log(&now, r);
                    }
                }
                LoggerInnerSink::Dyn(inner) => {
                    let sinks = inner.load();
                    for sink in sinks.iter() {
                        sink.log(&now, r);
                    }
                }
            }
        }
    }

    /// Can be call manually on program shutdown (If you have a buffered log sink)
    ///
    /// # Example
    ///
    /// ``` rust
    /// log::logger().flush();
    /// ```
    fn flush(&self) {
        if let Some(inner) = self.inner.as_ref() {
            match &inner.sinks {
                LoggerInnerSink::Once(inner) => {
                    for sink in inner.iter() {
                        sink.flush();
                    }
                }
                LoggerInnerSink::Dyn(inner) => {
                    let sinks = inner.load();
                    for sink in sinks.iter() {
                        sink.flush();
                    }
                }
            }
        }
    }
}

static GLOBAL_LOGGER: GlobalLoggerStatic = GlobalLoggerStatic::new();

/// log handle for panic hook
#[doc(hidden)]
pub fn log_panic(info: &std::panic::PanicHookInfo) {
    let bt = Backtrace::new();
    let mut record = log::Record::builder();
    record.level(log::Level::Error);
    if let Some(loc) = info.location() {
        record.file(Some(loc.file())).line(Some(loc.line()));
    }
    log::logger().log(&record.args(format_args!("panic occur: {}\ntrace: {:?}", info, bt)).build());
    eprint!("panic occur: {} at {:?}\ntrace: {:?}", info, info.location(), bt);
}

#[inline(always)]
fn panic_and_exit_hook(info: &std::panic::PanicHookInfo) {
    log_panic(info);
    log::logger().flush();
    let msg = format!("{}", info).to_string();
    std::panic::resume_unwind(Box::new(msg));
}

#[inline(always)]
fn panic_no_exit_hook(info: &std::panic::PanicHookInfo) {
    log_panic(info);
    eprint!("not debug version, so don't exit process");
    log::logger().flush();
}