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
// Copyright (c) 2021, BlockProject 3D
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//     * Neither the name of BlockProject 3D nor the names of its contributors
//       may be used to endorse or promote products derived from this software
//       without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// The reason why this is needed is because the 3 examples of usage of the Logger struct requires
// some context to not make it confusing.
#![allow(clippy::needless_doctest_main)]

mod backend;
mod internal;

use bp3d_fs::dirs::App;
use crossbeam_channel::Receiver;
use log::Level;
use once_cell::sync::Lazy;
use std::path::PathBuf;

/// Represents a log message in the [LogBuffer](crate::LogBuffer).
#[derive(Clone)]
pub struct LogMsg {
    /// The message string.
    pub msg: String,

    /// The crate name that issued this log.
    pub target: String,

    /// The log level.
    pub level: Level,
}

/// The log buffer type.
pub type LogBuffer = Receiver<LogMsg>;

/// Trait to allow getting a log directory from either a bp3d_fs::dirs::App or a String.
pub trait GetLogs {
    /// Gets the log directory as a PathBuf.
    ///
    /// Returns None if no directory could be computed.
    fn get_logs(self) -> Option<PathBuf>;
}

impl<'a> GetLogs for &'a String {
    fn get_logs(self) -> Option<PathBuf> {
        self.as_str().get_logs()
    }
}

impl<'a, 'b> GetLogs for &'a App<'b> {
    fn get_logs(self) -> Option<PathBuf> {
        self.get_logs().map(|v| v.into()).ok()
    }
}

impl<'a> GetLogs for &'a str {
    fn get_logs(self) -> Option<PathBuf> {
        let app = App::new(self);
        app.get_logs().map(|v| v.into()).ok()
    }
}

/// The base logger builder/initializer.
///
/// # Examples
///
/// The following example shows basic initialization of this logger.
/// ```
/// use bp3d_logger::Logger;
/// use log::info;
/// use log::LevelFilter;
///
/// fn main() {
///     Logger::new().add_stdout().add_file("my-app").run(|| {
///         log::set_max_level(LevelFilter::Info);
///         //...
///         info!("Example message");
///     });
/// }
/// ```
///
/// The following example shows initialization of this logger with a return value.
/// ```
/// use bp3d_logger::Logger;
/// use log::info;
/// use log::LevelFilter;
///
/// fn main() {
///     let code = Logger::new().add_stdout().add_file("my-app").run(|| {
///         log::set_max_level(LevelFilter::Info);
///         //...
///         info!("Example message");
///         0
///     });
///     std::process::exit(code);
/// }
/// ```
///
/// The following example shows initialization of this logger and use of the log buffer.
/// ```
/// use bp3d_logger::Logger;
/// use log::info;
/// use log::LevelFilter;
///
/// fn main() {
///     Logger::new().add_stdout().add_file("my-app").run(|| {
///         log::set_max_level(LevelFilter::Info);
///         bp3d_logger::enable_log_buffer(); // Enable log redirect pump into application channel.
///         //... application code with log redirect pump.
///         info!("Example message");
///         let l = bp3d_logger::get_log_buffer().recv().unwrap();// Capture the last log message.
///         println!("Last log message: {}", l.msg);
///         bp3d_logger::disable_log_buffer();
///         //... application code without log redirect pump.
///     });
/// }
/// ```
#[derive(Default)]
pub struct Logger {
    std: Option<backend::StdBackend>,
    file: Option<backend::FileBackend>,
}

impl Logger {
    /// Creates a new instance of a logger builder.
    pub fn new() -> Logger {
        Logger::default()
    }

    /// Enables stdout logging with automatic redirection of error logs to stderr.
    pub fn add_stdout(mut self) -> Self {
        self.std = Some(backend::StdBackend::new(true));
        self
    }

    /// Enables file logging to the given application.
    ///
    /// The application is given as a reference to [GetLogs](crate::GetLogs) to allow obtaining
    /// a log directory from various sources.
    ///
    /// If the log directory could not be found the function prints an error to stderr.
    pub fn add_file<T: GetLogs>(mut self, app: T) -> Self {
        if let Some(logs) = app.get_logs() {
            self.file = Some(backend::FileBackend::new(logs));
        } else {
            eprintln!("Failed to obtain application log directory");
        }
        self
    }

    /// Initializes the log implementation with this current configuration.
    ///
    /// NOTE: This takes a closure to flush all log buffers before returning. It is
    /// necessary to manually flush log buffers because this implementation uses threads
    /// to avoid blocking the main thread when issuing logs.
    ///
    /// NOTE 2: There are no safety concerns with running twice this function in the same
    /// application, only that calling this function may be slow due to thread management.
    pub fn run<R, F: FnOnce() -> R>(self, f: F) -> R {
        let _ = log::set_logger(&*BP3D_LOGGER); // Ignore the error
                                                // (we can't do anything if there's already a logger set;
                                                // unfortunately that is a limitation of the log crate)

        BP3D_LOGGER.start_new_thread(self); // Re-start the logging thread with the new configuration.
        BP3D_LOGGER.enable(true); // Enable logging.

        let res = f();

        // Disable the logger so further log requests are dropped.
        BP3D_LOGGER.enable(false);
        // Send termination command and join with logging thread.
        BP3D_LOGGER.terminate();
        // Clear by force all content of in memory log buffer.
        BP3D_LOGGER.clear_log_buffer();
        res
    }
}

static BP3D_LOGGER: Lazy<internal::LoggerImpl> = Lazy::new(internal::LoggerImpl::new);

/// Enables the log redirect pump.
pub fn enable_log_buffer() {
    BP3D_LOGGER.enable_log_buffer(true);
}

/// Disables the log redirect pump.
pub fn disable_log_buffer() {
    BP3D_LOGGER.enable_log_buffer(false);
    BP3D_LOGGER.clear_log_buffer();
}

/// Returns the buffer from the log redirect pump.
pub fn get_log_buffer() -> LogBuffer {
    BP3D_LOGGER.get_log_buffer()
}