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
//! # A specialized Logger for [`pt`](../libpt/index.html)
//!
//! This crate is part of [`pt`](../libpt/index.html), but can also be used as a standalone
//! module.
//!
//! For the library version, only the basic [`tracing`] is used, so that it is possible for
//! the end user to use the [`tracing`] frontend they desire.
//!
//! I did decide to create a [`Logger`] struct. This struct is mainly intended to be used with the
//! python module of [`pt`](../libpt/index.html), but is still just as usable in other contexts.
//! You can use this struct when use of the macros is not possible, but the macros should generally
//! be preferred.
//!
//! ## Technologies used for logging:
//! - [`tracing`]: base logging crate
//! - [`tracing_appender`]: Used to log to files
//! - [`tracing_subscriber`]: Used to do actual logging, formatting, to stdout
#![warn(clippy::pedantic, clippy::style, clippy::nursery)]

use std::{
    fmt::{self, Debug},
    path::PathBuf,
    sync::atomic::{AtomicBool, Ordering},
};

pub mod error;
use error::Error;

/// This is the magic dependency where the cool stuff happens
///
/// I'm just repackaging it a little to make it more ergonomic
pub use tracing;
pub use tracing::{debug, error, info, trace, warn, Level};
use tracing_subscriber::{
    fmt::format::FmtSpan, layer::SubscriberExt as _, util::SubscriberInitExt, Layer,
};

use anyhow::{bail, Result};
/// The log level used when none is specified
pub const DEFAULT_LOG_LEVEL: Level = Level::INFO;
/// The path where logs are stored when no path is given.
///
/// Currently, this is `/dev/null`, meaning they will be written to the void = discarded.
pub const DEFAULT_LOG_DIR: &str = "/dev/null";

static INITIALIZED: AtomicBool = AtomicBool::new(false);

/// Builder for a well configured [Logger]
///
/// This struct helps configure a global logger that can be used with either macros or methods, see
/// [Logger].
///
/// ## Examples
///
/// ```
/// # use libpt_log::{Logger, info};
/// # fn main() {
/// Logger::builder()
///     .uptime(true)
///     .build();
/// info!("hello world");
/// # }
///
/// ```
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
#[allow(clippy::struct_excessive_bools)] // it's just true/false values, not states, and I don't
                                         // need to reinvent the wheel
pub struct LoggerBuilder {
    /// create and log to logfiles
    log_to_file: bool,
    /// logfiles would be created here
    log_dir: PathBuf,
    /// use ANSI control sequences
    ansi: bool,
    /// show which source file produces a log
    display_filename: bool,
    /// show the log level of the message
    display_level: bool,
    /// show target context
    display_target: bool,
    /// sets the maximum verbosity level.
    ///
    /// For example, if set to [Error](Level::ERROR), logs at [Info](Level::INFO) will not be
    /// printed. If set to [Debug](Level::DEBUG), logs at [Info](Level::INFO) will be printed.
    max_level: Level,
    /// show the id of the thread that created this message
    display_thread_ids: bool,
    /// show the name of the thread that created this message
    display_thread_names: bool,
    /// show which line in the source file produces a log
    display_line_number: bool,
    /// splits a log over multiple lines, looks like a python traceback
    pretty: bool,
    /// show when the log was created
    show_time: bool,
    /// show timestamps as uptime (duration since the logger was initialized)
    uptime: bool,
    /// log when span things happen
    span_events: FmtSpan,
}

impl LoggerBuilder {
    /// use the configured settings to build and initialize a new global [Logger]
    ///
    /// This will build a functional [Logger]. You don't need to use the [Logger] struct, it's
    /// better to use the macros:
    ///
    /// * `error!`
    /// * `warn!`
    /// * `info!`
    /// * `debug!`
    /// * `trace!`
    ///
    /// instead of the methods of the [Logger] struct. You can however use the [Logger] struct in
    /// cases where usage of a macro is bad or you are somehow working with multiple loggers.
    ///
    /// ## Examples
    ///
    /// ```
    /// # use libpt_log::{Logger, info};
    /// # fn main() {
    /// Logger::builder()
    ///     .uptime(true)
    ///     .build();
    /// info!("hello world");
    /// # }
    ///
    /// ```
    /// # Errors
    ///
    /// This function will return an error if a global Logger was aready initialized. This module
    /// uses the [tracing] crate for logging, so if a [tracing] logger is initialized elsewhere,
    /// this method will error.
    #[allow(clippy::missing_panics_doc)]
    pub fn build(self) -> Result<Logger> {
        // only init if no init has been performed yet
        if INITIALIZED.load(Ordering::Relaxed) {
            warn!("trying to reinitialize the logger, ignoring");
            bail!(Error::Usage("logging is already initialized".to_string()));
        }
        let layer = tracing_subscriber::fmt::layer()
            .with_ansi(self.ansi)
            .with_target(self.display_target)
            .with_file(self.display_filename)
            .with_thread_ids(self.display_thread_ids)
            .with_line_number(self.display_line_number)
            .with_thread_names(self.display_thread_names)
            .with_span_events(self.span_events.clone())
            .with_filter(tracing::level_filters::LevelFilter::from_level(
                self.max_level,
            ));
        if self.log_to_file {
            tracing_subscriber::registry()
                .with(
                    layer.and_then(
                        tracing_subscriber::fmt::layer().with_writer(
                            self.logfile()?
                                .expect("logging to file is requested but logfile returned None"),
                        ),
                    ),
                )
                .init();
        } else {
            tracing_subscriber::registry().with(layer).init();
        }

        INITIALIZED.store(true, Ordering::Relaxed);
        Ok(Logger {})
    }

    /// Opens a new file for logging to.
    ///
    /// Format: `{log_dir}/{consumer_name}_2024-09-01.log`
    ///
    /// Will be none if [`Self::log_to_file`] is [false].
    fn logfile(&self) -> Result<Option<std::fs::File>> {
        if !self.log_to_file {
            return Err(Error::LogfileButNoFilelog.into());
        }
        let mut path = self.log_dir.clone();
        std::fs::create_dir_all(&path)?;
        path.push(format!(
            "{}_{}.log",
            libpt_core::get_crate_name().unwrap_or_else(|| "logfile".to_string()),
            chrono::Local::now().date_naive()
        ));
        let file = std::fs::File::create(path)?;
        Ok(Some(file))
    }

    /// enable or disable logging to and creating of logfiles
    ///
    /// If you want to log to a file, don't forget to set [`Self::log_dir`]!
    ///
    /// Default: false
    #[must_use]
    pub const fn log_to_file(mut self, log_to_file: bool) -> Self {
        self.log_to_file = log_to_file;
        self
    }

    /// set a directory where logfiles would be created in
    ///
    /// Enable or disable creation and logging to logfiles with [`log_to_file`](Self::log_to_file).
    ///
    /// Default: [`DEFAULT_LOG_DIR`] (/dev/null)
    #[must_use]
    pub fn log_dir(mut self, log_dir: PathBuf) -> Self {
        self.log_dir = log_dir;
        self
    }

    /// enable or disable ANSI control sequences
    ///
    /// Disabling ANSI control sequences might improve compatibility and readability when the logs
    /// are displayed by a program that does not interpret them.
    ///
    /// Keeping ANSI control sequences enabled has the disadvantage of added colors for the logs.
    ///
    /// Default: true
    #[must_use]
    pub const fn ansi(mut self, ansi: bool) -> Self {
        self.ansi = ansi;
        self
    }

    /// when making a log, display the source file in which a log was crated in
    ///
    /// Default: false
    #[must_use]
    pub const fn display_filename(mut self, display_filename: bool) -> Self {
        self.display_filename = display_filename;
        self
    }

    /// when making a log, display the time of the message
    ///
    /// Default: true
    #[must_use]
    pub const fn display_time(mut self, show_time: bool) -> Self {
        self.show_time = show_time;
        self
    }

    /// when making a log, display the log level of the message
    ///
    /// Default: true
    #[must_use]
    pub const fn display_level(mut self, display_level: bool) -> Self {
        self.display_level = display_level;
        self
    }

    /// show target context
    ///
    /// Default: false
    #[must_use]
    pub const fn display_target(mut self, display_target: bool) -> Self {
        self.display_target = display_target;
        self
    }

    /// show the id of the thread that created this message
    ///
    /// Default: false
    #[must_use]
    pub const fn display_thread_ids(mut self, display_thread_ids: bool) -> Self {
        self.display_thread_ids = display_thread_ids;
        self
    }

    /// show the name of the thread that created this message
    ///
    /// Default: false
    #[must_use]
    pub const fn display_thread_names(mut self, display_thread_names: bool) -> Self {
        self.display_thread_names = display_thread_names;
        self
    }

    /// show which line in the source file produces a log
    ///
    /// Default: false
    #[must_use]
    pub const fn display_line_number(mut self, display_line_number: bool) -> Self {
        self.display_line_number = display_line_number;
        self
    }

    /// splits a log over multiple lines, looks like a python traceback
    ///
    /// Default: false
    #[must_use]
    pub const fn pretty(mut self, pretty: bool) -> Self {
        self.pretty = pretty;
        self
    }

    /// show timestamps as uptime (duration since the logger was initialized)
    ///
    /// Default: false
    #[must_use]
    pub const fn uptime(mut self, uptime: bool) -> Self {
        self.uptime = uptime;
        self
    }

    /// set the lowest loglevel to be displayed
    ///
    /// Default: [`Level::INFO`]
    #[must_use]
    pub const fn set_level(mut self, max_level: Level) -> Self {
        self.max_level = max_level;
        self
    }

    /// set how span events are handled
    ///
    /// Default: [`FmtSpan::NONE`]
    #[must_use]
    pub const fn span_events(mut self, span_events: FmtSpan) -> Self {
        self.span_events = span_events;
        self
    }
}

impl Default for LoggerBuilder {
    fn default() -> Self {
        Self {
            log_to_file: false,
            log_dir: PathBuf::from(DEFAULT_LOG_DIR),
            ansi: true,
            display_filename: false,
            display_level: true,
            display_target: false,
            max_level: DEFAULT_LOG_LEVEL,
            display_thread_ids: false,
            display_thread_names: false,
            display_line_number: false,
            pretty: false,
            show_time: true,
            uptime: false,
            span_events: FmtSpan::NONE,
        }
    }
}

/// ## Logger for `libpt`
///
/// A logger is generally a functionality that let's you write information from your library or
/// application in a more structured manner than if you just wrote all information to `stdout` or
/// `stderr` with the likes of `println!` or `eprintln!`.
///
/// It offers writing to multiple targets, such as both the terminal and a log file, and allows
/// users to choose the verbosity of the information that gets printed by selecting a
/// [Loglevel](Level).
///
/// ## Levels
///
/// * [ERROR](Level::ERROR) – Something broke
/// * [WARN](Level::WARN) – Something is bad
/// * [INFO](Level::INFO) – Useful information for users
/// * [DEBUG](Level::DEBUG) – Useful information for developers
/// * [TRACE](Level::TRACE) – Very verbose information for developers (often for libraries)
///
/// ## Usage
///
/// You don't need to use the [Logger] struct, it's better to use the macros instead:
///
/// * [`error!`]
/// * [`warn!`]
/// * [`info!`]
/// * [`debug!`]
/// * [`trace!`]
///
/// You can however use the [Logger] struct in cases where usage of a macro is impossible or
/// you are somehow working with multiple loggers. The macros offer additional functionalities,
/// suck as full `format!` support and context, see [`tracing`], which we use as backend.
///
/// ## Examples
///
/// ```
/// # use libpt_log::{Logger, info};
/// # fn main() {
/// Logger::builder()
///     .uptime(true)
///     .build();
/// info!("hello world");
/// # }
///
/// ```
pub struct Logger;

/// ## Main implementation
impl Logger {
    /// Get a new [`LoggerBuilder`]
    #[must_use]
    pub fn builder() -> LoggerBuilder {
        LoggerBuilder::default()
    }

    /// ## logging at [`Level::ERROR`]
    pub fn error<T>(&self, printable: T)
    where
        T: fmt::Display,
    {
        error!("{}", printable);
    }
    /// ## logging at [`Level::WARN`]
    pub fn warn<T>(&self, printable: T)
    where
        T: fmt::Display,
    {
        warn!("{}", printable);
    }
    /// ## logging at [`Level::INFO`]
    pub fn info<T>(&self, printable: T)
    where
        T: fmt::Display,
    {
        info!("{}", printable);
    }
    /// ## logging at [`Level::DEBUG`]
    pub fn debug<T>(&self, printable: T)
    where
        T: fmt::Display,
    {
        debug!("{}", printable);
    }
    /// ## logging at [`Level::TRACE`]
    pub fn trace<T>(&self, printable: T)
    where
        T: fmt::Display,
    {
        trace!("{}", printable);
    }
}

impl fmt::Debug for Logger {
    /// ## DEBUG representation for [`Logger`]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Logger: {{initialized: {}}} ",
            INITIALIZED.load(Ordering::Relaxed)
        )
    }
}

impl Default for Logger {
    fn default() -> Self {
        LoggerBuilder::default()
            .build()
            .expect("building a Logger failed")
    }
}