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
//! simple-log is a very simple configuration log crates.
//!
//! # Quick Start
//!
//! To get you started quickly, the easiest and quick way to used with demo or test project
//!
//! ```no_run
//! #[macro_use]
//! extern crate log;
//!
//! fn main() -> Result<(), String> {
//!    simple_log::quick()?;
//!
//!    debug!("test builder debug");
//!    info!("test builder info");
//!    Ok(())
//!}
//! ```
//!
//! # Usage in project
//!
//! Configuration [LogConfig] in your project.
//!
//! ```no_run
//!#[macro_use]
//!extern crate log;
//!
//!use simple_log::LogConfigBuilder;
//!
//!fn main() -> Result<(), String> {
//!    let config = LogConfigBuilder::builder()
//!        .path("./log/builder_log.log")
//!        .size(1 * 100)
//!        .roll_count(10)
//!        .level("debug")
//!        .output_file()
//!        .output_console()
//!        .build();
//!
//!    simple_log::new(config)?;
//!    debug!("test builder debug");
//!    info!("test builder info");
//!    Ok(())
//!}
//! ```
//!
//! For the user guide and futher documentation, please read
//! [The Rust simple doc](https://github.com/baoyachi/simple-log).
//!

#[macro_use]
extern crate serde_derive;

mod out_kind;

use crate::out_kind::OutKind;
use log4rs::append::console::ConsoleAppender;
use log4rs::append::rolling_file::policy::compound::roll::fixed_window::FixedWindowRoller;
use log4rs::append::rolling_file::policy::compound::trigger::size::SizeTrigger;
use log4rs::append::rolling_file::policy::compound::CompoundPolicy;
use log4rs::append::rolling_file::RollingFileAppender;
use log4rs::config::{Appender, Config, Root};
use log4rs::encode::pattern::PatternEncoder;
use once_cell::sync::OnceCell;
use std::sync::Mutex;

type SimpleResult<T> = std::result::Result<T, String>;

/// Simple-log global config.
struct LogConf {
    log_config: LogConfig,
    handle: log4rs::Handle,
}

static LOG_CONF: OnceCell<Mutex<LogConf>> = OnceCell::new();

fn init_log_conf(log_config: LogConfig) -> SimpleResult<()> {
    let config = build_config(&log_config)?;
    let handle = log4rs::init_config(config).map_err(|e| e.to_string())?;
    LOG_CONF.get_or_init(|| Mutex::new(LogConf { log_config, handle }));
    Ok(())
}

pub fn update_log_conf(log_config: LogConfig) -> SimpleResult<LogConfig> {
    let log_conf = LOG_CONF.get().unwrap();
    let mut guard = log_conf.lock().unwrap();
    let config = build_config(&log_config)?;
    guard.log_config = log_config;
    guard.handle.set_config(config);
    Ok(guard.log_config.clone())
}

/// update simple-log global config log level.
///
/// # Examples
///
/// ```edition2018
/// fn main() -> Result<(), String> {
///     use simple_log::{LogConfigBuilder, update_log_level, log_level};
///     let config = LogConfigBuilder::builder()
///         .path("./log/builder_log.log")
///         .size(1 * 64)
///        .roll_count(10)
///        .level("debug")
///        .output_file()
///        .output_console()
///        .build();
///     simple_log::new(config)?;
///
///     //update log level
///     let config = update_log_level(log_level::DEBUG)?;
///     assert_eq!("debug",config.get_level());
///     Ok(())
/// }
/// ```
///
pub fn update_log_level<S: Into<String>>(level: S) -> SimpleResult<LogConfig> {
    let log_conf = LOG_CONF.get().unwrap();
    let mut guard = log_conf.lock().unwrap();
    guard.log_config.level = level.into();
    let config = build_config(&guard.log_config)?;
    guard.handle.set_config(config);
    Ok(guard.log_config.clone())
}

pub fn get_log_conf() -> SimpleResult<LogConfig> {
    let log_conf = LOG_CONF.get().unwrap();
    let config = log_conf.lock().unwrap().log_config.clone();
    Ok(config)
}

const SIMPLE_LOG_FILE: &str = "simple_log_file";
const SIMPLE_LOG_CONSOLE: &str = "simple_log_console";

#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct LogConfig {
    path: String,
    level: String,
    size: u64,
    out_kind: Vec<OutKind>,
    roll_count: u32,
}

impl LogConfig {
    pub fn get_path(&self) -> &String {
        &self.path
    }

    pub fn get_level(&self) -> &String {
        &self.level
    }

    pub fn get_size(&self) -> u64 {
        self.size
    }

    pub fn get_out_kind(&self) -> &Vec<OutKind> {
        &self.out_kind
    }

    pub fn get_roll_count(&self) -> u32 {
        self.roll_count
    }
}

/// The [LogConfig] with builder wrapper.
pub struct LogConfigBuilder(LogConfig);

impl LogConfigBuilder {
    /// Construct a [LogConfig] by [`LogConfigBuilder::builder`]
    ///
    /// # Examples
    ///
    /// ```edition2018
    /// use simple_log::{LogConfigBuilder, LogConfig};
    ///
    /// fn main() {
    ///     let builder:LogConfigBuilder = LogConfigBuilder::builder();
    ///     let log_config:LogConfig = builder.build();
    ///     println!("{:?}",log_config);
    /// }
    /// ```
    ///
    pub fn builder() -> Self {
        LogConfigBuilder(LogConfig::default())
    }

    /// Receive file write path.
    ///
    /// Simple-log output path when `OutKind` value is `File`.
    /// When `OutKind` value only is `console`,need ignore this method.
    ///
    /// # Examples
    ///
    /// ```edition2018
    ///
    /// fn main() {
    ///     use simple_log::LogConfigBuilder;
    ///     use simple_log::LogConfig;
    ///
    ///     let builder:LogConfigBuilder = LogConfigBuilder::builder().path("/tmp/log/simple_log.log");
    ///     let config:LogConfig = builder.build();
    ///     println!("{:?}",config);
    /// }
    /// ```
    ///
    pub fn path<S: Into<String>>(mut self, path: S) -> LogConfigBuilder {
        self.0.path = path.into();
        self
    }

    ///
    pub fn level<S: Into<String>>(mut self, level: S) -> LogConfigBuilder {
        self.0.level = level.into();
        self
    }

    pub fn size(mut self, size: u64) -> LogConfigBuilder {
        self.0.size = size;
        self
    }

    pub fn output_file(mut self) -> LogConfigBuilder {
        self.0.out_kind.push(OutKind::File);
        self
    }

    /// Configuration [LogConfigBuilder] with log output with console.
    ///
    /// If your application build with `--release`.This method should not be used
    /// `output_file` method is recommended.
    /// This is usually used with `debug` or `test` mode.
    pub fn output_console(mut self) -> LogConfigBuilder {
        self.0.out_kind.push(OutKind::Console);
        self
    }

    pub fn roll_count(mut self, roll_count: u32) -> LogConfigBuilder {
        self.0.roll_count = roll_count;
        self
    }

    /// Constructs a new `LogConfig` .
    ///
    /// # Examples
    ///
    /// ```edition2018
    /// fn main() {
    ///     use simple_log::LogConfigBuilder;
    ///     let builder:LogConfigBuilder = LogConfigBuilder::builder();
    ///     let config = LogConfigBuilder::builder()
    ///         .path("./log/builder_log.log")
    ///         .size(1 * 100)
    ///        .roll_count(10)
    ///        .level("debug")
    ///        .output_file()
    ///        .output_console()
    ///        .build();
    ///     println!("{:?}",config);
    /// }
    /// ```
    pub fn build(self) -> LogConfig {
        self.0
    }
}

/// The [new] method provide init simple-log instance with config.
///
/// This method need pass [LogConfig] param. Your can use [LogConfigBuilder] `build` [LogConfig].
/// Also you can use [serde] with `Deserialize` init `LogConfig`.
///
/// # Examples
///
/// ```no_run
/// #[macro_use]
/// extern crate log;
///
/// use simple_log::LogConfigBuilder;
///
/// fn main() -> Result<(), String> {
///    let config = LogConfigBuilder::builder()
///            .path("./log/builder_log.log")
///            .size(1 * 100)
///            .roll_count(10)
///            .level("info")
///            .output_file()
///            .output_console()
///            .build();
///     simple_log::new(config)?;
///     debug!("test builder debug");
///     info!("test builder info");
///     Ok(())
/// }
/// ```
///
pub fn new(log_config: LogConfig) -> SimpleResult<()> {
    let mut log_config = log_config;
    init_default_log(&mut log_config);
    init_log_conf(log_config)?;
    Ok(())
}

/// This method can quick init simple-log with no configuration.
///
/// If your just want use in demo or test project. Your can use this method.
/// The [quick] method not add any params in method. It's so easy.
///
/// The [`LogConfig`] filed just used inner default value.
///
/// ```bash
///     path: ./tmp/simple_log.log //output file path
///     level: debug //log level
///     size: 10 //single log file size with unit:MB. 10MB eq:10*1024*1024
///     out_kind:[file,console] //Output to file and terminal at the same time
///     roll_count:10 //At the same time, it can save 10 files endwith .gz
///```
///
/// If you don't want use [quick] method.Also can use [new] method.
///
/// # Examples
///
/// ```edition2018
/// #[macro_use]
/// extern crate log;
///
/// fn main() -> Result<(), String> {
///     simple_log::quick()?;
///
///     debug!("test builder debug");
///     info!("test builder info");
///     Ok(())
/// }
/// ```
pub fn quick() -> SimpleResult<()> {
    let mut config = LogConfig::default();
    init_default_log(&mut config);
    init_log_conf(config)?;
    Ok(())
}

/// Provide init simple-log instance with stdout console on terminal.
///
/// Method receive log level one of [log_level] mod.
pub fn console(level: String) -> SimpleResult<()> {
    let mut config = LogConfig::default();
    config.level = level;
    config.out_kind = vec![OutKind::Console];
    init_log_conf(config)?;
    Ok(())
}

///Provide init simple-log instance with write file.
///
/// The param `path` is either an absolute path or lacking a leading `/`, relative to the `cwd` of your [LogConfig].
/// The param `level` config log level with [log_level].
/// The param `size` config single file size(MB).
/// The param `roll_count` config single file size(MB).
/// The file extension of the pattern is `.gz`,the archive files will be gzip-compressed.
pub fn file<S: Into<String>>(path: S, level: S, size: u64, roll_count: u32) -> SimpleResult<()> {
    let config = LogConfig {
        path: path.into(),
        level: level.into(),
        size,
        out_kind: vec![OutKind::File],
        roll_count,
    };
    init_log_conf(config)?;
    Ok(())
}

fn build_config(log: &LogConfig) -> SimpleResult<Config> {
    let mut config_builder = Config::builder();
    let mut root_builder = Root::builder();
    for kind in &log.out_kind {
        match kind {
            OutKind::File => {
                config_builder = config_builder
                    .appender(Appender::builder().build(SIMPLE_LOG_FILE, file_appender(log)?));
                root_builder = root_builder.appender(SIMPLE_LOG_FILE);
            }
            OutKind::Console => {
                let console = ConsoleAppender::builder()
                    .encoder(Box::new(encoder()))
                    .build();
                config_builder = config_builder
                    .appender(Appender::builder().build(SIMPLE_LOG_CONSOLE, Box::new(console)));
                root_builder = root_builder.appender(SIMPLE_LOG_CONSOLE);
            }
        }
    }

    let config = config_builder
        .build(root_builder.build(log_level::form_log_level(&log.level)))
        .map_err(|e| e.to_string())?;
    Ok(config)
}

/// check log config,and give default value
fn init_default_log(log: &mut LogConfig) {
    if log.path.trim().is_empty() {
        log.path = "./tmp/simple_log.log".to_string();
    }

    if log.size == 0 {
        log.size = 10 //1MB:1*1024*1024
    }

    if log.roll_count == 0 {
        log.roll_count = 10
    }

    if log.level.is_empty() {
        log.level = log_level::DEBUG.to_string()
    }

    if log.out_kind.is_empty() {
        log.out_kind
            .append(&mut vec![OutKind::Console, OutKind::File])
    }
}

fn encoder() -> PatternEncoder {
    PatternEncoder::new("{d(%Y-%m-%d %H:%M:%S:%f)} [{l}] <{M}:{L}>:{m}\n")
}

fn file_appender(log: &LogConfig) -> SimpleResult<Box<RollingFileAppender>> {
    let roll = FixedWindowRoller::builder()
        .base(0)
        .build(format!("{}.{{}}.gz", log.path).as_str(), log.roll_count)
        .map_err(|e| e.to_string())?;

    let trigger = SizeTrigger::new(log.size * 1024 * 1024);

    let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roll));

    let logfile = RollingFileAppender::builder()
        .encoder(Box::new(encoder()))
        .build(log.path.clone(), Box::new(policy))
        .map_err(|e| e.to_string())?;

    Ok(Box::new(logfile))
}

pub mod log_level {
    use log::LevelFilter;

    pub const TRACE: &str = "trace";
    pub const DEBUG: &str = "debug";
    pub const INFO: &str = "info";
    pub const WARN: &str = "warn";
    pub const ERROR: &str = "error";

    /// convert log level str to [LevelFilter].
    ///
    /// The default log level use [LevelFilter::Debug].
    ///
    /// # Examples
    ///
    /// ```edition2018
    ///
    /// fn main() {
    ///     use simple_log::log_level::form_log_level;
    ///     use log::LevelFilter;
    ///     let level = form_log_level("warn");
    ///     assert_eq!(level,LevelFilter::Warn);
    ///
    ///     let level = form_log_level("error");
    ///     assert_eq!(level,LevelFilter::Error);
    ///
    ///     let level = form_log_level("no");
    ///     assert_eq!(level,LevelFilter::Debug);
    /// }
    /// ```
    ///
    pub fn form_log_level(level: &str) -> LevelFilter {
        match level {
            TRACE => LevelFilter::Trace,
            DEBUG => LevelFilter::Debug,
            INFO => LevelFilter::Info,
            WARN => LevelFilter::Warn,
            ERROR => LevelFilter::Error,
            _ => LevelFilter::Debug,
        }
    }
}