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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
use std::io::Write;
use flexi_error::FlexiLoggerError;
use LevelFilter;
use log;
use regex::Regex;
#[cfg(feature = "specfile")]
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::env;
#[cfg(feature = "specfile")]
use std::fs;
#[cfg(feature = "specfile")]
use std::ffi::OsStr;
#[cfg(feature = "specfile")]
use std::io::Read;
#[cfg(feature = "specfile")]
use std::path::{Path, PathBuf};
#[cfg(feature = "specfile")]
use toml;

///
/// Immutable struct that defines which loglines are to be written,
/// based on the module, the log level, and the text.
///
/// The loglevel specification via string (relevant for methods
/// [parse()](struct.LogSpecification.html#method.parse) and
/// [env()](struct.LogSpecification.html#method.env))
/// works essentially like with `env_logger`,
/// but we are a bit more tolerant with spaces. Its functionality can be
/// described with some Backus-Naur-form:
///
/// ```text
/// <log_level_spec> ::= single_log_level_spec[{,single_log_level_spec}][/<text_filter>]
/// <single_log_level_spec> ::= <path_to_module>|<log_level>|<path_to_module>=<log_level>
/// <text_filter> ::= <regex>
/// ```
///
/// * Examples:
///
///   * `"info"`: all logs with info, warn, or error level are written
///   * `"crate1"`: all logs of this crate are written, but nothing else
///   * `"warn, crate2::mod_a=debug, mod_x::mod_y=trace"`: all crates log warnings and erors,
///     `mod_a` additional debug messages, and `mod_x::mod_y` is fully traced
///
/// * If you just specify the module, without `log_level`, all levels will be traced for this
///   module.
/// * If you just specify a log level, this will be applied as default to all modules without
///   explicit log level assigment.
///   (You see that for modules named error, warn, info, debug or trace,
///   it is necessary to specify their loglevel explicit).
/// * The module names are compared as Strings, with the side effect that a specified module filter
///   affects all modules whose name starts with this String.<br>
///   Example: ```"foo"``` affects e.g.
///
///   * `foo`
///   * `foo::bar`
///   * `foobaz` (!)
///   * `foobaz::bar` (!)
///
/// The optional text filter is applied for all modules.
///
/// Note that external module names are to be specified like in ```"extern crate ..."```, i.e.,
/// for crates with a dash in their name this means: the dash is to be replaced with
/// the underscore (e.g. ```karl_heinz```, not ```karl-heinz```).
#[derive(Clone, Debug)]
pub struct LogSpecification {
    module_filters: Vec<ModuleFilter>,
    textfilter: Option<Regex>,
}

/// Defines which loglevel filter to use for a given module (or as default, if no module is given).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ModuleFilter {
    pub module_name: Option<String>,
    pub level_filter: LevelFilter,
}

impl LogSpecification {
    #[doc(hidden)]
    pub fn reconfigure(&mut self, other_spec: LogSpecification) {
        self.module_filters = other_spec.module_filters;
        self.textfilter = other_spec.textfilter;
    }

    /// Implementation of Log::enabled() with easier testable signature
    pub fn enabled(&self, level: log::Level, target_module: &str) -> bool {
        // Search for the longest match, the vector is assumed to be pre-sorted.
        for module_filter in &self.module_filters {
            match module_filter.module_name {
                Some(ref module_name) if !target_module.starts_with(&**module_name) => {}
                Some(..) | None => return level <= module_filter.level_filter,
            }
        }
        false
    }

    /// Returns a log specification from a String.
    pub fn parse(spec: &str) -> LogSpecification {
        let mut dirs = Vec::<ModuleFilter>::new();

        let mut parts = spec.split('/');
        let mods = parts.next();
        let filter = parts.next();
        if parts.next().is_some() {
            println!(
                "warning: invalid logging spec '{}', ignoring it (too many '/'s)",
                spec
            );
            return LogSpecification::default(LevelFilter::Off).finalize();
        }
        mods.map(|m| {
            for s in m.split(',') {
                let s = s.trim();
                if s.is_empty() {
                    continue;
                }
                let mut parts = s.split('=');
                let (log_level, name) =
                    match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) {
                        (Some(part0), None, None) => {
                            if contains_dash(part0) {
                                println!(
                                    "warning: invalid part in logging spec '{}', contains a dash, \
                                     ignoring it",
                                    part0
                                );
                                continue;
                            }
                            // if the single argument is a log-level string or number,
                            // treat that as a global fallback
                            match part0.trim().parse() {
                                Ok(num) => (num, None),
                                Err(_) => (LevelFilter::max(), Some(part0)),
                            }
                        }
                        (Some(part0), Some(""), None) => {
                            if contains_dash(part0) {
                                println!(
                                    "warning: invalid part in logging spec '{}', contains a dash, \
                                     ignoring it",
                                    part0
                                );
                                continue;
                            }

                            (LevelFilter::max(), Some(part0))
                        }
                        (Some(part0), Some(part1), None) => {
                            if contains_dash(part0) {
                                println!(
                                    "warning: invalid part in logging spec '{}', contains a dash, \
                                     ignoring it",
                                    part0
                                );
                                continue;
                            }
                            match part1.trim().parse() {
                                Ok(num) => (num, Some(part0.trim())),
                                _ => {
                                    println!(
                                        "warning: invalid part in logging spec '{}', ignoring it",
                                        part1
                                    );
                                    continue;
                                }
                            }
                        }
                        _ => {
                            println!("warning: invalid part in logging spec '{}', ignoring it", s);
                            continue;
                        }
                    };
                dirs.push(ModuleFilter {
                    module_name: name.map(|s| s.to_string()),
                    level_filter: log_level,
                });
            }
        });

        let textfilter = filter.and_then(|filter| match Regex::new(filter) {
            Ok(re) => Some(re),
            Err(e) => {
                println!("warning: invalid regex filter - {}", e);
                None
            }
        });

        LogSpecification {
            module_filters: dirs.level_sort(),
            textfilter,
        }
    }

    /// Returns a log specification based on the value of the environment variable RUST_LOG,
    /// or an empty one.
    pub fn env() -> LogSpecification {
        match env::var("RUST_LOG") {
            Ok(spec) => LogSpecification::parse(&spec),
            Err(..) => LogSpecification::default(LevelFilter::Off).finalize(),
        }
    }

    /// Returns a log specification based on the value of the environment variable RUST_LOG,
    /// or on the given String.
    pub fn env_or_parse<S: AsRef<str>>(given_spec: S) -> LogSpecification {
        match env::var("RUST_LOG") {
            Ok(spec) => LogSpecification::parse(&spec),
            Err(..) => LogSpecification::parse(given_spec.as_ref()),
        }
    }

    /// If the specfile does not exist, try to create it, with the current spec as content,
    /// under the specified name.
    #[cfg(feature = "specfile")]
    pub fn ensure_specfile_is_valid(&self, specfile: &PathBuf) -> Result<(), FlexiLoggerError> {
        if specfile
            .extension()
            .unwrap_or_else(|| OsStr::new(""))
            .to_str()
            .unwrap_or("") != "toml"
        {
            return Err(FlexiLoggerError::Parse(
                "only files with suffix toml are supported".to_owned(),
            ));
        }

        if Path::is_file(specfile) {
            return Ok(());
        }

        if let Some(specfolder) = specfile.parent() {
            if let Err(e) = fs::DirBuilder::new().recursive(true).create(specfolder) {
                error!(
                    "cannot create the folder for the logspec file under the specified name \
                     {:?}, caused by: {}",
                    &specfile, e
                );
                return Err(FlexiLoggerError::from(e));
            }
        }

        match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(specfile)
        {
            Err(e) => {
                error!(
                    "cannot create an initial logspec file under the specified name \
                     {:?}, caused by: {}",
                    &specfile, e
                );
                return Err(FlexiLoggerError::from(e));
            }
            Ok(mut file) => {
                self.to_toml(&mut file)?;
            }
        };

        Ok(())
    }

    /// Reads a log specification from a file.
    #[cfg(feature = "specfile")]
    pub fn file<P: AsRef<Path>>(specfile: P) -> Result<LogSpecification, FlexiLoggerError> {
        // Open the file in read-only mode.
        let mut file = fs::File::open(specfile)?;

        // Read the content toml file as an instance of `LogSpecFileFormat`.
        let mut s = String::new();
        file.read_to_string(&mut s)?;
        LogSpecification::from_toml(&s)
    }

    //
    #[cfg(feature = "specfile")]
    fn from_toml(s: &str) -> Result<LogSpecification, FlexiLoggerError> {
        #[derive(Clone, Debug, Deserialize)]
        struct LogSpecFileFormat {
            pub global_level: Option<String>,
            pub global_pattern: Option<String>,
            pub modules: BTreeMap<String, String>,
        }

        let logspec_ff: LogSpecFileFormat = toml::from_str(s)?;
        let mut module_filters = Vec::<ModuleFilter>::new();

        if let Some(s) = logspec_ff.global_level {
            module_filters.push(ModuleFilter {
                module_name: None,
                level_filter: parse_level_filter(s)?,
            });
        }

        for (k, v) in logspec_ff.modules {
            module_filters.push(ModuleFilter {
                module_name: Some(k),
                level_filter: parse_level_filter(v)?,
            });
        }

        let textfilter = match logspec_ff.global_pattern {
            None => None,
            Some(s) => match Regex::new(&s) {
                Ok(re) => Some(re),
                Err(e) => {
                    println!("warning: invalid regex filter - {}", e);
                    None
                }
            },
        };

        Ok(LogSpecification {
            module_filters: module_filters.level_sort(),
            textfilter,
        })
    }

    /// Serializes itself in toml format
    pub fn to_toml(&self, w: &mut Write) -> Result<(), FlexiLoggerError> {
        w.write_all(b"### Optional: Default log level\n")?;
        let last = self.module_filters.last();
        if last.is_some() && last.as_ref().unwrap().module_name.is_none() {
            w.write_all(
                format!(
                    "global_level = '{}'\n",
                    last.as_ref()
                        .unwrap()
                        .level_filter
                        .to_string()
                        .to_lowercase()
                ).as_bytes(),
            )?;
        } else {
            w.write_all(b"#global_level = 'info'\n")?;
        }

        w.write_all(
            b"\n### Optional: specify a regular expression to suppress all messages that don't match\n",
        )?;
        w.write_all(b"#global_pattern = 'foo'\n")?;

        w.write_all(
            b"\n### Specific log levels per module are optionally defined in this section\n",
        )?;
        w.write_all(b"[modules]\n")?;
        if self.module_filters.is_empty() || self.module_filters[0].module_name.is_none() {
            w.write_all(b"#'mod1' = 'warn'\n")?;
            w.write_all(b"#'mod2' = 'debug'\n")?;
            w.write_all(b"#'mod2::mod3' = 'trace'\n")?;
        }
        for mf in &self.module_filters {
            if mf.module_name.is_some() {
                w.write_all(
                    format!(
                        "'{}' = '{}'\n",
                        mf.module_name.as_ref().unwrap(),
                        mf.level_filter.to_string().to_lowercase()
                    ).as_bytes(),
                )?;
            }
        }
        Ok(())
    }

    /// Creates a LogSpecBuilder, setting the default log level.
    pub fn default(level_filter: LevelFilter) -> LogSpecBuilder {
        LogSpecBuilder::from_module_filters(&[
            ModuleFilter {
                module_name: None,
                level_filter,
            },
        ])
    }

    /// Provides a reference to the module filters.
    pub fn module_filters(&self) -> &Vec<ModuleFilter> {
        &self.module_filters
    }

    /// Provides a reference to the text filter.
    pub fn text_filter(&self) -> &Option<Regex> {
        &(self.textfilter)
    }
}

#[cfg(feature = "specfile")]
fn parse_level_filter<S: AsRef<str>>(s: S) -> Result<LevelFilter, FlexiLoggerError> {
    Ok(match s.as_ref().to_lowercase().as_ref() {
        "off" => LevelFilter::Off,
        "error" => LevelFilter::Error,
        "warn" => LevelFilter::Warn,
        "info" => LevelFilter::Info,
        "debug" => LevelFilter::Debug,
        "trace" => LevelFilter::Trace,
        _ => {
            return Err(FlexiLoggerError::Parse(format!(
                "unknown level filter: {}",
                s.as_ref()
            )))
        }
    })
}

fn contains_dash(s: &str) -> bool {
    s.find('-') != None
}

/// Builder for `LogSpecification`.
#[derive(Clone, Default)]
pub struct LogSpecBuilder {
    module_filters: HashMap<Option<String>, LevelFilter>,
}

impl LogSpecBuilder {
    /// Creates a LogSpecBuilder with all logging turned off.
    pub fn new() -> LogSpecBuilder {
        let mut modfilmap = HashMap::new();
        modfilmap.insert(None, LevelFilter::Off);
        LogSpecBuilder {
            module_filters: modfilmap,
        }
    }

    /// Creates a LogSpecBuilder from given module filters.
    pub fn from_module_filters(module_filters: &[ModuleFilter]) -> LogSpecBuilder {
        let mut modfilmap = HashMap::new();
        for mf in module_filters {
            modfilmap.insert(mf.module_name.clone(), mf.level_filter);
        }
        LogSpecBuilder {
            module_filters: modfilmap,
        }
    }

    /// Adds a default log level filter, or updates the default log level filter.
    pub fn default(&mut self, lf: LevelFilter) -> &mut LogSpecBuilder {
        self.module_filters.insert(None, lf);
        self
    }

    /// Adds a log level filter, or updates the log level filter, for a module.
    pub fn module<M: AsRef<str>>(
        &mut self,
        module_name: M,
        lf: LevelFilter,
    ) -> &mut LogSpecBuilder {
        self.module_filters
            .insert(Some(module_name.as_ref().to_owned()), lf);
        self
    }

    /// Adds a log level filter, or updates the log level filter, for a module.
    pub fn remove<M: AsRef<str>>(&mut self, module_name: M) -> &mut LogSpecBuilder {
        self.module_filters
            .remove(&Some(module_name.as_ref().to_owned()));
        self
    }

    /// Creates a log specification without text filter.
    pub fn finalize(self) -> LogSpecification {
        LogSpecification {
            module_filters: self.module_filters.into_vec_module_filter(),
            textfilter: None,
        }
    }

    /// Creates a log specification with text filter.
    pub fn finalize_with_textfilter(self, tf: Regex) -> LogSpecification {
        LogSpecification {
            module_filters: self.module_filters.into_vec_module_filter(),
            textfilter: Some(tf),
        }
    }

    /// Creates a log specification without being consumed.
    pub fn build(&self) -> LogSpecification {
        LogSpecification {
            module_filters: self.module_filters.clone().into_vec_module_filter(),
            textfilter: None,
        }
    }

    /// Creates a log specification without being consumed, optionally with a text filter.
    pub fn build_with_textfilter(&self, tf: Option<Regex>) -> LogSpecification {
        LogSpecification {
            module_filters: self.module_filters.clone().into_vec_module_filter(),
            textfilter: tf,
        }
    }
}

trait IntoVecModuleFilter {
    fn into_vec_module_filter(self) -> Vec<ModuleFilter>;
}
impl IntoVecModuleFilter for HashMap<Option<String>, LevelFilter> {
    fn into_vec_module_filter(self) -> Vec<ModuleFilter> {
        let mf: Vec<ModuleFilter> = self.into_iter()
            .map(|(k, v)| ModuleFilter {
                module_name: k,
                level_filter: v,
            })
            .collect();
        mf.level_sort()
    }
}

trait LevelSort {
    fn level_sort(self) -> Vec<ModuleFilter>;
}
impl LevelSort for Vec<ModuleFilter> {
    /// Sort the module filters by length of their name,
    /// this allows a little more efficient lookup at runtime.
    fn level_sort(mut self) -> Vec<ModuleFilter> {
        self.sort_by(|a, b| {
            let alen = a.module_name.as_ref().map(|a| a.len()).unwrap_or(0);
            let blen = b.module_name.as_ref().map(|b| b.len()).unwrap_or(0);
            blen.cmp(&alen)
        });
        self
    }
}

#[cfg(features = "specfile")]
#[cfg(test)]
mod tests {
    extern crate log;
    use {LogSpecBuilder, LogSpecification};
    use log::{Level, LevelFilter};

    #[test]
    fn specfile() {
        compare_specs(
            "[modules]\n\
             ",
            "",
        );

        compare_specs(
            "global_level = 'info'\n\
             \n\
             [modules]\n\
             ",
            "info",
        );

        compare_specs(
            "global_level = 'info'\n\
             \n\
             [modules]\n\
             'mod1::mod2' = 'debug'\n\
             'mod3' = 'trace'\n\
             ",
            "info, mod1::mod2 = debug, mod3 = trace",
        );

        compare_specs(
            "global_level = 'info'\n\
             global_pattern = 'Foo'\n\
             \n\
             [modules]\n\
             'mod1::mod2' = 'debug'\n\
             'mod3' = 'trace'\n\
             ",
            "info, mod1::mod2 = debug, mod3 = trace /Foo",
        );
    }

    fn compare_specs(s1: &str, s2: &str) {
        let ls1 = LogSpecification::from_toml(s1).unwrap();
        let ls2 = LogSpecification::parse(s2);

        assert_eq!(ls1.module_filters, ls2.module_filters);
        assert_eq!(ls1.textfilter.is_none(), ls2.textfilter.is_none());
        if ls1.textfilter.is_some() && ls2.textfilter.is_some() {
            assert_eq!(
                ls1.textfilter.unwrap().to_string(),
                ls2.textfilter.unwrap().to_string()
            );
        }
    }

    #[test]
    fn parse_logging_spec_valid() {
        let spec = LogSpecification::parse("crate1::mod1=error,crate1::mod2,crate2=debug");
        assert_eq!(spec.module_filters().len(), 3);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate1::mod1".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Error);

        assert_eq!(
            spec.module_filters()[1].module_name,
            Some("crate1::mod2".to_string())
        );
        assert_eq!(spec.module_filters()[1].level_filter, LevelFilter::max());

        assert_eq!(
            spec.module_filters()[2].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[2].level_filter, LevelFilter::Debug);

        assert!(spec.text_filter().is_none());
    }

    #[test]
    fn parse_logging_spec_invalid_crate() {
        // test parse_logging_spec with multiple = in specification
        let spec = LogSpecification::parse("crate1::mod1=warn=info,crate2=debug");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Debug);
        assert!(spec.text_filter().is_none());
    }

    #[test]
    fn parse_logging_spec_invalid_log_level() {
        // test parse_logging_spec with 'noNumber' as log level
        let spec = LogSpecification::parse("crate1::mod1=noNumber,crate2=debug");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Debug);
        assert!(spec.text_filter().is_none());
    }

    #[test]
    fn parse_logging_spec_string_log_level() {
        // test parse_logging_spec with 'warn' as log level
        let spec = LogSpecification::parse("crate1::mod1=wrong, crate2=warn");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Warn);
        assert!(spec.text_filter().is_none());
    }

    #[test]
    fn parse_logging_spec_empty_log_level() {
        // test parse_logging_spec with '' as log level
        let spec = LogSpecification::parse("crate1::mod1=wrong, crate2=");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::max());
        assert!(spec.text_filter().is_none());
    }

    #[test]
    fn parse_logging_spec_global() {
        // test parse_logging_spec with no crate
        let spec = LogSpecification::parse("warn,crate2=debug");
        assert_eq!(spec.module_filters().len(), 2);

        assert_eq!(spec.module_filters()[1].module_name, None);
        assert_eq!(spec.module_filters()[1].level_filter, LevelFilter::Warn);

        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Debug);

        assert!(spec.text_filter().is_none());
    }

    #[test]
    fn parse_logging_spec_valid_filter() {
        let spec = LogSpecification::parse(" crate1::mod1 = error , crate1::mod2,crate2=debug/abc");
        assert_eq!(spec.module_filters().len(), 3);

        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate1::mod1".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Error);

        assert_eq!(
            spec.module_filters()[1].module_name,
            Some("crate1::mod2".to_string())
        );
        assert_eq!(spec.module_filters()[1].level_filter, LevelFilter::max());

        assert_eq!(
            spec.module_filters()[2].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[2].level_filter, LevelFilter::Debug);
        assert!(
            spec.text_filter().is_some()
                && spec.text_filter().as_ref().unwrap().to_string() == "abc"
        );
    }

    #[test]
    fn parse_logging_spec_invalid_crate_filter() {
        let spec = LogSpecification::parse("crate1::mod1=error=warn,crate2=debug/a.c");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Debug);
        assert!(
            spec.text_filter().is_some()
                && spec.text_filter().as_ref().unwrap().to_string() == "a.c"
        );
    }

    #[test]
    fn parse_logging_spec_invalid_crate_with_dash() {
        let spec = LogSpecification::parse("karl-heinz::mod1=warn,crate2=debug/a.c");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate2".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::Debug);
        assert!(
            spec.text_filter().is_some()
                && spec.text_filter().as_ref().unwrap().to_string() == "a.c"
        );
    }

    #[test]
    fn parse_logging_spec_empty_with_filter() {
        let spec = LogSpecification::parse("crate1/a*c");
        assert_eq!(spec.module_filters().len(), 1);
        assert_eq!(
            spec.module_filters()[0].module_name,
            Some("crate1".to_string())
        );
        assert_eq!(spec.module_filters()[0].level_filter, LevelFilter::max());
        assert!(
            spec.text_filter().is_some()
                && spec.text_filter().as_ref().unwrap().to_string() == "a*c"
        );
    }

    #[test]
    fn reuse_logspec_builder() {
        let mut builder = LogSpecBuilder::new();

        builder.default(LevelFilter::Info);
        builder.module("carlo", LevelFilter::Debug);
        builder.module("toni", LevelFilter::Warn);
        let spec1 = builder.build();

        assert_eq!(
            spec1.module_filters()[0].module_name,
            Some("carlo".to_string())
        );
        assert_eq!(spec1.module_filters()[0].level_filter, LevelFilter::Debug);

        assert_eq!(
            spec1.module_filters()[1].module_name,
            Some("toni".to_string())
        );
        assert_eq!(spec1.module_filters()[1].level_filter, LevelFilter::Warn);

        assert_eq!(spec1.module_filters().len(), 3);
        assert_eq!(spec1.module_filters()[2].module_name, None);
        assert_eq!(spec1.module_filters()[2].level_filter, LevelFilter::Info);

        builder.default(LevelFilter::Error);
        builder.remove("carlo");
        builder.module("greta", LevelFilter::Trace);
        let spec2 = builder.build();

        assert_eq!(spec2.module_filters().len(), 3);
        assert_eq!(spec2.module_filters()[2].module_name, None);
        assert_eq!(spec2.module_filters()[2].level_filter, LevelFilter::Error);

        assert_eq!(
            spec2.module_filters()[0].module_name,
            Some("greta".to_string())
        );
        assert_eq!(spec2.module_filters()[0].level_filter, LevelFilter::Trace);

        assert_eq!(
            spec2.module_filters()[1].module_name,
            Some("toni".to_string())
        );
        assert_eq!(spec2.module_filters()[1].level_filter, LevelFilter::Warn);
    }

    ///////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////
    #[test]
    fn match_full_path() {
        let spec = LogSpecification::parse("crate2=info,crate1::mod1=warn");
        assert!(spec.enabled(Level::Warn, "crate1::mod1"));
        assert!(!spec.enabled(Level::Info, "crate1::mod1"));
        assert!(spec.enabled(Level::Info, "crate2"));
        assert!(!spec.enabled(Level::Debug, "crate2"));
    }

    #[test]
    fn no_match() {
        let spec = LogSpecification::parse("crate2=info,crate1::mod1=warn");
        assert!(!spec.enabled(Level::Warn, "crate3"));
    }

    #[test]
    fn match_beginning() {
        let spec = LogSpecification::parse("crate2=info,crate1::mod1=warn");
        assert!(spec.enabled(Level::Info, "crate2::mod1"));
    }

    #[test]
    fn match_beginning_longest_match() {
        let spec = LogSpecification::parse(
            "abcd = info, abcd::mod1 = error, klmn::mod = debug, klmn = info",
        );
        assert!(spec.enabled(Level::Error, "abcd::mod1::foo"));
        assert!(!spec.enabled(Level::Warn, "abcd::mod1::foo"));
        assert!(spec.enabled(Level::Warn, "abcd::mod2::foo"));
        assert!(!spec.enabled(Level::Debug, "abcd::mod2::foo"));

        assert!(!spec.enabled(Level::Debug, "klmn"));
        assert!(!spec.enabled(Level::Debug, "klmn::foo::bar"));
        assert!(spec.enabled(Level::Info, "klmn::foo::bar"));
    }

    #[test]
    fn match_default1() {
        let spec = LogSpecification::parse("info,abcd::mod1=warn");
        assert!(spec.enabled(Level::Warn, "abcd::mod1"));
        assert!(spec.enabled(Level::Info, "crate2::mod2"));
    }

    #[test]
    fn match_default2() {
        let spec = LogSpecification::parse("modxyz=error, info, abcd::mod1=warn");
        assert!(spec.enabled(Level::Warn, "abcd::mod1"));
        assert!(spec.enabled(Level::Info, "crate2::mod2"));
    }

    #[test]
    fn zero_level() {
        let spec = LogSpecification::parse("info,crate1::mod1=off");
        assert!(!spec.enabled(Level::Error, "crate1::mod1"));
        assert!(spec.enabled(Level::Info, "crate2::mod2"));
    }

}