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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
use std::borrow::Cow;
use std::io::Write;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};
use std::{cmp, fmt, fs, io};

#[cfg(feature = "syslog-4")]
use std::collections::HashMap;

use log::{self, Log};

use {log_impl, Filter, FormatCallback, Formatter};

#[cfg(feature = "syslog-3")]
use syslog_3;
#[cfg(feature = "syslog-4")]
use {Syslog4Rfc3164Logger, Syslog4Rfc5424Logger};

/// The base dispatch logger.
///
/// This allows for formatting log records, limiting what records can be passed
/// through, and then dispatching records to other dispatch loggers or output
/// loggers.
///
/// Note that all methods are position-insensitive.
/// `Dispatch::new().format(a).chain(b)` produces the exact same result
/// as `Dispatch::new().chain(b).format(a)`. Given this, it is preferred to put
/// 'format' and other modifiers before 'chain' for the sake of clarity.
///
/// Example usage demonstrating all features:
///
/// ```no_run
/// # // no_run because this creates log files.
/// #[macro_use]
/// extern crate log;
/// extern crate fern;
///
/// use std::{fs, io};
///
/// # fn setup_logger() -> Result<(), fern::InitError> {
/// fern::Dispatch::new()
///     .format(|out, message, record| {
///         out.finish(format_args!(
///             "[{}][{}] {}",
///             record.level(),
///             record.target(),
///             message,
///         ))
///     })
///     .chain(
///         fern::Dispatch::new()
///             // by default only accept warn messages
///             .level(log::LevelFilter::Warn)
///             // accept info messages from the current crate too
///             .level_for("my_crate", log::LevelFilter::Info)
///             // `io::Stdout`, `io::Stderr` and `io::File` can be directly passed in.
///             .chain(io::stdout()),
///     )
///     .chain(
///         fern::Dispatch::new()
///             // output all messages
///             .level(log::LevelFilter::Trace)
///             // except for hyper, in that case only show info messages
///             .level_for("hyper", log::LevelFilter::Info)
///             // `log_file(x)` equates to
///             // `OpenOptions::new().write(true).append(true).create(true).open(x)`
///             .chain(fern::log_file("persistent-log.log")?)
///             .chain(fs::OpenOptions::new()
///                 .write(true)
///                 .create(true)
///                 .truncate(true)
///                 .create(true)
///                 .open("/tmp/temp.log")?),
///     )
///     .chain(
///         fern::Dispatch::new()
///             .level(log::LevelFilter::Error)
///             .filter(|_meta_data| {
///                 // as an example, randomly reject half of the messages
///                 # /*
///                 rand::random()
///                 # */
///                 # true
///             })
///             .chain(io::stderr()),
///     )
///     // and finally, set as the global logger!
///     .apply()?;
/// # Ok(())
/// # }
/// #
/// # fn main() { setup_logger().expect("failed to set up logger") }
/// ```
#[must_use = "this is only a logger configuration and must be consumed with into_log() or apply()"]
pub struct Dispatch {
    format: Option<Box<Formatter>>,
    children: Vec<OutputInner>,
    default_level: log::LevelFilter,
    levels: Vec<(Cow<'static, str>, log::LevelFilter)>,
    filters: Vec<Box<Filter>>,
}

/// Logger which is usable as an output for multiple other loggers.
///
/// This struct contains a built logger stored in an [`Arc`], and can be
/// safely cloned.
///
/// See [`Dispatch::into_shared`].
///
/// [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
/// [`Dispatch::into_shared`]: struct.Dispatch.html#method.into_shared
#[derive(Clone)]
pub struct SharedDispatch {
    inner: Arc<log_impl::Dispatch>,
    min_level: log::LevelFilter,
}

impl Dispatch {
    /// Creates a dispatch, which will initially do nothing.
    #[inline]
    pub fn new() -> Self {
        Dispatch {
            format: None,
            children: Vec::new(),
            default_level: log::LevelFilter::Trace,
            levels: Vec::new(),
            filters: Vec::new(),
        }
    }

    /// Sets the formatter of this dispatch. The closure should accept a
    /// callback, a message and a log record, and write the resulting
    /// format to the writer.
    ///
    /// The log record is passed for completeness, but the `args()` method of
    /// the record should be ignored, and the [`fmt::Arguments`] given
    /// should be used instead. `record.args()` may be used to retrieve the
    /// _original_ log message, but in order to allow for true log
    /// chaining, formatters should use the given message instead whenever
    /// including the message in the output.
    ///
    /// To avoid all allocation of intermediate results, the formatter is
    /// "completed" by calling a callback, which then calls the rest of the
    /// logging chain with the new formatted message. The callback object keeps
    /// track of if it was called or not via a stack boolean as well, so if
    /// you don't use `out.finish` the log message will continue down
    /// the logger chain unformatted.
    ///
    /// [`fmt::Arguments`]: https://doc.rust-lang.org/std/fmt/struct.Arguments.html
    ///
    /// Example usage:
    ///
    /// ```
    /// fern::Dispatch::new().format(|out, message, record| {
    ///     out.finish(format_args!(
    ///         "[{}][{}] {}",
    ///         record.level(),
    ///         record.target(),
    ///         message
    ///     ))
    /// })
    ///     # .into_log();
    /// ```
    #[inline]
    pub fn format<F>(mut self, formatter: F) -> Self
    where
        F: Fn(FormatCallback, &fmt::Arguments, &log::Record) + Sync + Send + 'static,
    {
        self.format = Some(Box::new(formatter));
        self
    }

    /// Adds a child to this dispatch.
    ///
    /// All log records which pass all filters will be formatted and then sent
    /// to all child loggers in sequence.
    ///
    /// Note: If the child logger is also a Dispatch, and cannot accept any log
    /// records, it will be dropped. This only happens if the child either
    /// has no children itself, or has a minimum log level of
    /// [`LevelFilter::Off`].
    ///
    /// [`LevelFilter::Off`]: https://docs.rs/log/0.4/log/enum.LevelFilter.html#variant.Off
    ///
    /// Example usage:
    ///
    /// ```
    /// fern::Dispatch::new()
    ///     .chain(fern::Dispatch::new().chain(std::io::stdout()))
    ///     # .into_log();
    /// ```
    #[inline]
    pub fn chain<T: Into<Output>>(mut self, logger: T) -> Self {
        self.children.push(logger.into().0);
        self
    }

    /// Sets the overarching level filter for this logger. All messages not
    /// already filtered by something set by [`Dispatch::level_for`] will
    /// be affected.
    ///
    /// All messages filtered will be discarded if less severe than the given
    /// level.
    ///
    /// Default level is [`LevelFilter::Trace`].
    ///
    /// [`Dispatch::level_for`]: #method.level_for
    /// [`LevelFilter::Trace`]: https://docs.rs/log/0.4/log/enum.LevelFilter.html#variant.Trace
    ///
    /// Example usage:
    ///
    /// ```
    /// # extern crate log;
    /// # extern crate fern;
    /// #
    /// # fn main() {
    /// fern::Dispatch::new()
    ///     .level(log::LevelFilter::Info)
    ///     # .into_log();
    /// # }
    /// ```
    #[inline]
    pub fn level(mut self, level: log::LevelFilter) -> Self {
        self.default_level = level;
        self
    }

    /// Sets a per-target log level filter. Default target for log messages is
    /// `crate_name::module_name` or
    /// `crate_name` for logs in the crate root. Targets can also be set with
    /// `info!(target: "target-name", ...)`.
    ///
    /// For each log record fern will first try to match the most specific
    /// level_for, and then progressively more general ones until either a
    /// matching level is found, or the default level is used.
    ///
    /// For example, a log for the target `hyper::http::h1` will first test a
    /// level_for for `hyper::http::h1`, then for `hyper::http`, then for
    /// `hyper`, then use the default level.
    ///
    /// Examples:
    ///
    /// A program wants to include a lot of debugging output, but the library
    /// "hyper" is known to work well, so debug output from it should be
    /// excluded:
    ///
    /// ```
    /// # extern crate log;
    /// # extern crate fern;
    /// #
    /// # fn main() {
    /// fern::Dispatch::new()
    ///     .level(log::LevelFilter::Trace)
    ///     .level_for("hyper", log::LevelFilter::Info)
    ///     # .into_log();
    /// # }
    /// ```
    ///
    /// A program has a ton of debug output per-module, but there is so much
    /// that debugging more than one module at a time is not very useful.
    /// The command line accepts a list of modules to debug, while keeping the
    /// rest of the program at info level:
    ///
    /// ```
    /// # extern crate log;
    /// # extern crate fern;
    /// #
    /// fn setup_logging<T, I>(verbose_modules: T) -> Result<(), fern::InitError>
    /// where
    ///     I: AsRef<str>,
    ///     T: IntoIterator<Item = I>,
    /// {
    ///     let mut config = fern::Dispatch::new()
    ///         .level(log::LevelFilter::Info);
    ///
    ///     for module_name in verbose_modules {
    ///         config = config.level_for(
    ///             format!("my_crate_name::{}", module_name.as_ref()),
    ///             log::LevelFilter::Debug,
    ///         );
    ///     }
    ///
    ///     config.chain(std::io::stdout()).apply()?;
    ///
    ///     Ok(())
    /// }
    /// #
    /// # // we're ok with apply() failing.
    /// # fn main() { let _ = setup_logging(&["hi"]); }
    /// ```
    #[inline]
    pub fn level_for<T: Into<Cow<'static, str>>>(
        mut self,
        module: T,
        level: log::LevelFilter,
    ) -> Self {
        let module = module.into();

        if let Some((index, _)) = self
            .levels
            .iter()
            .enumerate()
            .find(|&(_, &(ref name, _))| name == &module)
        {
            self.levels.remove(index);
        }

        self.levels.push((module, level));
        self
    }

    /// Adds a custom filter which can reject messages passing through this
    /// logger.
    ///
    /// The logger will continue to process log records only if all filters
    /// return `true`.
    ///
    /// [`Dispatch::level`] and [`Dispatch::level_for`] are preferred if
    /// applicable.
    ///
    /// [`Dispatch::level`]: #method.level
    /// [`Dispatch::level_for`]: #method.level_for
    ///
    /// Example usage:
    ///
    /// This sends error level messages to stderr and others to stdout.
    ///
    /// ```
    /// # extern crate log;
    /// # extern crate fern;
    /// #
    /// # fn main() {
    /// fern::Dispatch::new()
    ///     .level(log::LevelFilter::Info)
    ///     .chain(
    ///         fern::Dispatch::new()
    ///             .filter(|metadata| {
    ///                 // Reject messages with the `Error` log level.
    ///                 metadata.level() != log::LevelFilter::Error
    ///             })
    ///             .chain(std::io::stderr()),
    ///     )
    ///     .chain(
    ///         fern::Dispatch::new()
    ///             .level(log::LevelFilter::Error)
    ///             .chain(std::io::stdout()),
    ///     )
    ///     # .into_log();
    /// # }
    #[inline]
    pub fn filter<F>(mut self, filter: F) -> Self
    where
        F: Fn(&log::Metadata) -> bool + Send + Sync + 'static,
    {
        self.filters.push(Box::new(filter));
        self
    }

    /// Builds this dispatch and stores it in a clonable structure containing
    /// an [`Arc`].
    ///
    /// Once "shared", the dispatch can be used as an output for multiple other
    /// dispatch loggers.
    ///
    /// Example usage:
    ///
    /// This separates info and warn messages, sending info to stdout + a log
    /// file, and warn to stderr + the same log file. Shared is used so the
    /// program only opens "file.log" once.
    ///
    /// ```no_run
    /// # extern crate log;
    /// # extern crate fern;
    /// #
    /// # fn setup_logger() -> Result<(), fern::InitError> {
    ///
    /// let file_out = fern::Dispatch::new()
    ///     .chain(fern::log_file("file.log")?)
    ///     .into_shared();
    ///
    /// let info_out = fern::Dispatch::new()
    ///     .level(log::LevelFilter::Debug)
    ///     .filter(|metadata|
    ///         // keep only info and debug (reject warn and error)
    ///         metadata.level() <= log::Level::Info)
    ///     .chain(std::io::stdout())
    ///     .chain(file_out.clone());
    ///
    /// let warn_out = fern::Dispatch::new()
    ///     .level(log::LevelFilter::Warn)
    ///     .chain(std::io::stderr())
    ///     .chain(file_out);
    ///
    /// fern::Dispatch::new()
    ///     .chain(info_out)
    ///     .chain(warn_out)
    ///     .apply();
    ///
    /// # Ok(())
    /// # }
    /// #
    /// # fn main() { setup_logger().expect("failed to set up logger"); }
    /// ```
    ///
    /// [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html
    pub fn into_shared(self) -> SharedDispatch {
        let (min_level, dispatch) = self.into_dispatch();

        SharedDispatch {
            inner: Arc::new(dispatch),
            min_level: min_level,
        }
    }

    /// Builds this into the actual logger implementation.
    ///
    /// This could probably be refactored, but having everything in one place
    /// is also nice.
    fn into_dispatch(self) -> (log::LevelFilter, log_impl::Dispatch) {
        let Dispatch {
            format,
            children,
            default_level,
            levels,
            mut filters,
        } = self;

        let mut max_child_level = log::LevelFilter::Off;

        let output = children
            .into_iter()
            .flat_map(|child| match child {
                OutputInner::Stdout { stream, line_sep } => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Stdout(log_impl::Stdout {
                        stream: stream,
                        line_sep: line_sep,
                    }))
                }
                OutputInner::Stderr { stream, line_sep } => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Stderr(log_impl::Stderr {
                        stream: stream,
                        line_sep: line_sep,
                    }))
                }
                OutputInner::File { stream, line_sep } => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::File(log_impl::File {
                        stream: Mutex::new(io::BufWriter::new(stream)),
                        line_sep: line_sep,
                    }))
                }
                OutputInner::Writer { stream, line_sep } => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Writer(log_impl::Writer {
                        stream: Mutex::new(stream),
                        line_sep: line_sep,
                    }))
                }
                OutputInner::Sender { stream, line_sep } => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Sender(log_impl::Sender {
                        stream: Mutex::new(stream),
                        line_sep: line_sep,
                    }))
                }
                #[cfg(feature = "syslog-3")]
                OutputInner::Syslog3(log) => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Syslog3(log_impl::Syslog3 { inner: log }))
                }
                #[cfg(feature = "syslog-4")]
                OutputInner::Syslog4Rfc3164(logger) => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Syslog4Rfc3164(log_impl::Syslog4Rfc3164 {
                        inner: Mutex::new(logger),
                    }))
                }
                #[cfg(feature = "syslog-4")]
                OutputInner::Syslog4Rfc5424 { logger, transform } => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Syslog4Rfc5424(log_impl::Syslog4Rfc5424 {
                        inner: Mutex::new(logger),
                        transform,
                    }))
                }
                OutputInner::Panic => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::Panic(log_impl::Panic))
                }
                OutputInner::Dispatch(child_dispatch) => {
                    let (child_level, child) = child_dispatch.into_dispatch();
                    if child_level > log::LevelFilter::Off {
                        max_child_level = cmp::max(max_child_level, child_level);
                        Some(log_impl::Output::Dispatch(child))
                    } else {
                        None
                    }
                }
                OutputInner::SharedDispatch(child_dispatch) => {
                    let SharedDispatch {
                        inner: child,
                        min_level: child_level,
                    } = child_dispatch;

                    if child_level > log::LevelFilter::Off {
                        max_child_level = cmp::max(max_child_level, child_level);
                        Some(log_impl::Output::SharedDispatch(child))
                    } else {
                        None
                    }
                }
                OutputInner::OtherBoxed(child_log) => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::OtherBoxed(child_log))
                }
                OutputInner::OtherStatic(child_log) => {
                    max_child_level = log::LevelFilter::Trace;
                    Some(log_impl::Output::OtherStatic(child_log))
                }
            })
            .collect();

        let min_level = levels
            .iter()
            .map(|t| t.1)
            .max()
            .map_or(default_level, |lvl| cmp::max(lvl, default_level));
        let real_min = cmp::min(min_level, max_child_level);

        filters.shrink_to_fit();

        let dispatch = log_impl::Dispatch {
            output: output,
            default_level: default_level,
            levels: levels.into(),
            format: format,
            filters: filters,
        };

        (real_min, dispatch)
    }

    /// Builds this logger into a `Box<log::Log>` and calculates the minimum
    /// log level needed to have any effect.
    ///
    /// While this method is exposed publicly, [`Dispatch::apply`] is typically
    /// used instead.
    ///
    /// The returned LevelFilter is a calculation for all level filters of this
    /// logger and child loggers, and is the minimum log level needed to
    /// for a record to have any chance of passing through this logger.
    ///
    /// [`Dispatch::apply`]: #method.apply
    ///
    /// Example usage:
    ///
    /// ```
    /// # extern crate log;
    /// # extern crate fern;
    /// #
    /// # fn main() {
    /// let (min_level, log) = fern::Dispatch::new()
    ///     .level(log::LevelFilter::Info)
    ///     .chain(std::io::stdout())
    ///     .into_log();
    ///
    /// assert_eq!(min_level, log::LevelFilter::Info);
    /// # }
    /// ```
    pub fn into_log(self) -> (log::LevelFilter, Box<log::Log>) {
        let (level, logger) = self.into_dispatch();
        if level == log::LevelFilter::Off {
            (level, Box::new(log_impl::Null))
        } else {
            (level, Box::new(logger))
        }
    }

    /// Builds this logger and instantiates it as the global [`log`] logger.
    ///
    /// # Errors:
    ///
    /// This function will return an error if a global logger has already been
    /// set to a previous logger.
    ///
    /// [`log`]: https://github.com/rust-lang-nursery/log
    pub fn apply(self) -> Result<(), log::SetLoggerError> {
        let (max_level, log) = self.into_log();

        log::set_boxed_logger(log)?;
        log::set_max_level(max_level);

        Ok(())
    }
}

/// This enum contains various outputs that you can send messages to.
enum OutputInner {
    /// Prints all messages to stdout with `line_sep` separator.
    Stdout {
        stream: io::Stdout,
        line_sep: Cow<'static, str>,
    },
    /// Prints all messages to stderr with `line_sep` separator.
    Stderr {
        stream: io::Stderr,
        line_sep: Cow<'static, str>,
    },
    /// Writes all messages to file with `line_sep` separator.
    File {
        stream: fs::File,
        line_sep: Cow<'static, str>,
    },
    /// Writes all messages to the writer with `line_sep` separator.
    Writer {
        stream: Box<Write + Send>,
        line_sep: Cow<'static, str>,
    },
    /// Writes all messages to mpst::Sender with `line_sep` separator.
    Sender {
        stream: Sender<String>,
        line_sep: Cow<'static, str>,
    },
    /// Passes all messages to other dispatch.
    Dispatch(Dispatch),
    /// Passes all messages to other dispatch that's shared.
    SharedDispatch(SharedDispatch),
    /// Passes all messages to other logger.
    OtherBoxed(Box<Log>),
    /// Passes all messages to other logger.
    OtherStatic(&'static Log),
    /// Passes all messages to the syslog.
    #[cfg(feature = "syslog-3")]
    Syslog3(syslog_3::Logger),
    /// Passes all messages to the syslog.
    #[cfg(feature = "syslog-4")]
    Syslog4Rfc3164(Syslog4Rfc3164Logger),
    /// Sends all messages through the transform then passes to the syslog.
    #[cfg(feature = "syslog-4")]
    Syslog4Rfc5424 {
        logger: Syslog4Rfc5424Logger,
        transform: Box<
            Fn(&log::Record) -> (i32, HashMap<String, HashMap<String, String>>, String)
                + Sync
                + Send,
        >,
    },
    /// Panics with messages text for all messages.
    Panic,
}

/// Logger which will panic whenever anything is logged. The panic
/// will be exactly the message of the log.
///
/// `Panic` is useful primarily as a secondary logger, filtered by warning or
/// error.
///
/// # Examples
///
/// This configuration will output all messages to stdout and panic if an Error
/// message is sent.
///
/// ```
/// # extern crate fern;
/// # extern crate log;
/// fern::Dispatch::new()
///     // format, etc.
///     .chain(std::io::stdout())
///     .chain(
///         fern::Dispatch::new()
///             .level(log::LevelFilter::Error)
///             .chain(fern::Panic)
///     )
///     # /*
///     .apply()?;
///     # */ .into_log();
/// ```
///
/// This sets up a "panic on warn+" logger, and ignores errors so it can be
/// called multiple times.
///
/// This might be useful in test setup, for example, to disallow warn-level
/// messages.
///
/// ```no_run
/// # extern crate fern;
/// # extern crate log;
/// fn setup_panic_logging() {
///     fern::Dispatch::new()
///         .level(log::LevelFilter::Warn)
///         .chain(fern::Panic)
///         .apply()
///         // ignore errors from setting up logging twice
///         .ok();
/// }
/// ```
pub struct Panic;

/// Configuration for a logger output.
pub struct Output(OutputInner);

impl From<Dispatch> for Output {
    /// Creates an output logger forwarding all messages to the dispatch.
    fn from(log: Dispatch) -> Self {
        Output(OutputInner::Dispatch(log))
    }
}

impl From<SharedDispatch> for Output {
    /// Creates an output logger forwarding all messages to the dispatch.
    fn from(log: SharedDispatch) -> Self {
        Output(OutputInner::SharedDispatch(log))
    }
}

impl From<Box<Log>> for Output {
    /// Creates an output logger forwarding all messages to the custom logger.
    fn from(log: Box<Log>) -> Self {
        Output(OutputInner::OtherBoxed(log))
    }
}

impl From<&'static Log> for Output {
    /// Creates an output logger forwarding all messages to the custom logger.
    fn from(log: &'static Log) -> Self {
        Output(OutputInner::OtherStatic(log))
    }
}

impl From<fs::File> for Output {
    /// Creates an output logger which writes all messages to the file with
    /// `\n` as the separator.
    ///
    /// File writes are buffered and flushed once per log record.
    fn from(file: fs::File) -> Self {
        Output(OutputInner::File {
            stream: file,
            line_sep: "\n".into(),
        })
    }
}

impl From<Box<Write + Send>> for Output {
    /// Creates an output logger which writes all messages to the writer with
    /// `\n` as the separator.
    ///
    /// This does no buffering and it is up to the writer to do buffering as
    /// needed (eg. wrap it in `BufWriter`). However, flush is called after
    /// each log record.
    fn from(writer: Box<Write + Send>) -> Self {
        Output(OutputInner::Writer {
            stream: writer,
            line_sep: "\n".into(),
        })
    }
}

impl From<io::Stdout> for Output {
    /// Creates an output logger which writes all messages to stdout with the
    /// given handle and `\n` as the separator.
    fn from(stream: io::Stdout) -> Self {
        Output(OutputInner::Stdout {
            stream: stream,
            line_sep: "\n".into(),
        })
    }
}

impl From<io::Stderr> for Output {
    /// Creates an output logger which writes all messages to stderr with the
    /// given handle and `\n` as the separator.
    fn from(stream: io::Stderr) -> Self {
        Output(OutputInner::Stderr {
            stream: stream,
            line_sep: "\n".into(),
        })
    }
}

impl From<Sender<String>> for Output {
    /// Creates an output logger which writes all messages to the given
    /// mpsc::Sender with  '\n' as the separator.
    ///
    /// All messages sent to the mpsc channel are suffixed with '\n'.
    fn from(stream: Sender<String>) -> Self {
        Output(OutputInner::Sender {
            stream: stream,
            line_sep: "\n".into(),
        })
    }
}

#[cfg(feature = "syslog-3")]
impl From<syslog_3::Logger> for Output {
    /// Creates an output logger which writes all messages to the given syslog
    /// output.
    ///
    /// Log levels are translated trace => debug, debug => debug, info =>
    /// informational, warn => warning, and error => error.
    ///
    /// This requires the `"syslog-3"` feature.
    fn from(log: syslog_3::Logger) -> Self {
        Output(OutputInner::Syslog3(log))
    }
}

#[cfg(feature = "syslog-3")]
impl From<Box<syslog_3::Logger>> for Output {
    /// Creates an output logger which writes all messages to the given syslog
    /// output.
    ///
    /// Log levels are translated trace => debug, debug => debug, info =>
    /// informational, warn => warning, and error => error.
    ///
    /// Note that while this takes a Box<Logger> for convenience (syslog
    /// methods return Boxes), it will be immediately unboxed upon storage
    /// in the configuration structure. This will create a configuration
    /// identical to that created by passing a raw `syslog::Logger`.
    ///
    /// This requires the `"syslog-3"` feature.
    fn from(log: Box<syslog_3::Logger>) -> Self {
        Output(OutputInner::Syslog3(*log))
    }
}

#[cfg(feature = "syslog-4")]
impl From<Syslog4Rfc3164Logger> for Output {
    /// Creates an output logger which writes all messages to the given syslog.
    ///
    /// Log levels are translated trace => debug, debug => debug, info =>
    /// informational, warn => warning, and error => error.
    ///
    /// Note that due to https://github.com/Geal/rust-syslog/issues/41,
    /// logging to this backend requires one allocation per log call.
    ///
    /// This is for RFC 3164 loggers. To use an RFC 5424 logger, use the
    /// [`Output::syslog_5424`] helper method.
    ///
    /// This requires the `"syslog-4"` feature.
    fn from(log: Syslog4Rfc3164Logger) -> Self {
        Output(OutputInner::Syslog4Rfc3164(log))
    }
}

impl From<Panic> for Output {
    /// Creates an output logger which will panic with message text for all
    /// messages.
    fn from(_: Panic) -> Self {
        Output(OutputInner::Panic)
    }
}

impl Output {
    /// Returns a file logger using a custom separator.
    ///
    /// If the default separator of `\n` is acceptable, an [`fs::File`]
    /// instance can be passed into [`Dispatch::chain`] directly.
    ///
    /// ```no_run
    /// # fn setup_logger() -> Result<(), fern::InitError> {
    /// fern::Dispatch::new()
    ///     .chain(std::fs::File::create("log")?)
    ///     # .into_log();
    /// # Ok(())
    /// # }
    /// #
    /// # fn main() { setup_logger().expect("failed to set up logger"); }
    /// ```
    ///
    /// ```no_run
    /// # fn setup_logger() -> Result<(), fern::InitError> {
    /// fern::Dispatch::new()
    ///     .chain(fern::log_file("log")?)
    ///     # .into_log();
    /// # Ok(())
    /// # }
    /// #
    /// # fn main() { setup_logger().expect("failed to set up logger"); }
    /// ```
    ///
    /// Example usage (using [`fern::log_file`]):
    ///
    /// ```no_run
    /// # fn setup_logger() -> Result<(), fern::InitError> {
    /// fern::Dispatch::new()
    ///     .chain(fern::Output::file(fern::log_file("log")?, "\r\n"))
    ///     # .into_log();
    /// # Ok(())
    /// # }
    /// #
    /// # fn main() { setup_logger().expect("failed to set up logger"); }
    /// ```
    ///
    /// [`fs::File`]: https://doc.rust-lang.org/std/fs/struct.File.html
    /// [`Dispatch::chain`]: struct.Dispatch.html#method.chain
    /// [`fern::log_file`]: fn.log_file.html
    pub fn file<T: Into<Cow<'static, str>>>(file: fs::File, line_sep: T) -> Self {
        Output(OutputInner::File {
            stream: file,
            line_sep: line_sep.into(),
        })
    }

    /// Returns a logger using arbitrary write object and custom separator.
    ///
    /// If the default separator of `\n` is acceptable, an `Box<Write + Send>`
    /// instance can be passed into [`Dispatch::chain`] directly.
    ///
    /// ```no_run
    /// # fn setup_logger() -> Result<(), fern::InitError> {
    /// // Anything implementing 'Write' works.
    /// let mut writer = std::io::Cursor::new(Vec::<u8>::new());
    ///
    /// fern::Dispatch::new()
    ///     // as long as we explicitly cast into a type-erased Box
    ///     .chain(Box::new(writer) as Box<std::io::Write + Send>)
    ///     # .into_log();
    /// #     Ok(())
    /// # }
    /// #
    /// # fn main() { setup_logger().expect("failed to set up logger"); }
    /// ```
    ///
    /// Example usage:
    ///
    /// ```no_run
    /// # fn setup_logger() -> Result<(), fern::InitError> {
    /// let writer = Box::new(std::io::Cursor::new(Vec::<u8>::new()));
    ///
    /// fern::Dispatch::new()
    ///     .chain(fern::Output::writer(writer, "\r\n"))
    ///     # .into_log();
    /// #     Ok(())
    /// # }
    /// #
    /// # fn main() { setup_logger().expect("failed to set up logger"); }
    /// ```
    ///
    /// [`Dispatch::chain`]: struct.Dispatch.html#method.chain
    pub fn writer<T: Into<Cow<'static, str>>>(writer: Box<Write + Send>, line_sep: T) -> Self {
        Output(OutputInner::Writer {
            stream: writer,
            line_sep: line_sep.into(),
        })
    }

    /// Returns an stdout logger using a custom separator.
    ///
    /// If the default separator of `\n` is acceptable, an `io::Stdout`
    /// instance can be passed into `Dispatch::chain()` directly.
    ///
    /// ```
    /// fern::Dispatch::new()
    ///     .chain(std::io::stdout())
    ///     # .into_log();
    /// ```
    ///
    /// Example usage:
    ///
    /// ```
    /// fern::Dispatch::new()
    ///     // some unix tools use null bytes as message terminators so
    ///     // newlines in messages can be treated differently.
    ///     .chain(fern::Output::stdout("\0"))
    ///     # .into_log();
    /// ```
    pub fn stdout<T: Into<Cow<'static, str>>>(line_sep: T) -> Self {
        Output(OutputInner::Stdout {
            stream: io::stdout(),
            line_sep: line_sep.into(),
        })
    }

    /// Returns an stderr logger using a custom separator.
    ///
    /// If the default separator of `\n` is acceptable, an `io::Stderr`
    /// instance can be passed into `Dispatch::chain()` directly.
    ///
    /// ```
    /// fern::Dispatch::new()
    ///     .chain(std::io::stderr())
    ///     # .into_log();
    /// ```
    ///
    /// Example usage:
    ///
    /// ```
    /// fern::Dispatch::new()
    ///     .chain(fern::Output::stderr("\n\n\n"))
    ///     # .into_log();
    /// ```
    pub fn stderr<T: Into<Cow<'static, str>>>(line_sep: T) -> Self {
        Output(OutputInner::Stderr {
            stream: io::stderr(),
            line_sep: line_sep.into(),
        })
    }

    /// Returns a mpsc::Sender logger using a custom separator.
    ///
    /// If the default separator of `\n` is acceptable, an
    /// `mpsc::Sender<String>` instance can be passed into `Dispatch::
    /// chain()` directly.
    ///
    /// Each log message will be suffixed with the separator, then sent as a
    /// single String to the given sender.
    ///
    /// ```
    /// use std::sync::mpsc::channel;
    ///
    /// let (tx, rx) = channel();
    /// fern::Dispatch::new()
    ///     .chain(tx)
    ///     # .into_log();
    /// ```
    pub fn sender<T: Into<Cow<'static, str>>>(sender: Sender<String>, line_sep: T) -> Self {
        Output(OutputInner::Sender {
            stream: sender,
            line_sep: line_sep.into(),
        })
    }

    /// Returns a logger which logs into an RFC5424 syslog.
    ///
    /// This method takes an additional transform method to turn the log data
    /// into RFC5424 data.
    ///
    /// I've honestly got no clue what the expected keys and values are for
    /// this kind of logging, so I'm just going to link [the rfc] instead.
    ///
    /// If you're an expert on syslog logging and would like to contribute
    /// an example to put here, it would be gladly accepted!
    ///
    /// This requires the `"syslog-4"` feature.
    ///
    /// [the rfc]: https://tools.ietf.org/html/rfc5424
    #[cfg(feature = "syslog-4")]
    pub fn syslog_5424<F>(logger: Syslog4Rfc5424Logger, transform: F) -> Self
    where
        F: Fn(&log::Record) -> (i32, HashMap<String, HashMap<String, String>>, String)
            + Sync
            + Send
            + 'static,
    {
        Output(OutputInner::Syslog4Rfc5424 {
            logger,
            transform: Box::new(transform),
        })
    }

    /// Returns a logger which simply calls the given function with each message.
    ///
    /// The function will be called inline in the thread the log occurs on.
    ///
    /// Example usage:
    ///
    /// ```
    /// fern::Dispatch::new()
    ///     .chain(fern::Output::call(|record| {
    ///         // this is mundane, but you can do anything here.
    ///         println!("{}", record.args());
    ///     }))
    ///     # .into_log();
    /// ```
    pub fn call<F>(func: F) -> Self
    where
        F: Fn(&log::Record) + Sync + Send + 'static,
    {
        struct CallShim<F>(F);
        impl<F> log::Log for CallShim<F>
        where
            F: Fn(&log::Record) + Sync + Send + 'static,
        {
            fn enabled(&self, _: &log::Metadata) -> bool {
                true
            }
            fn log(&self, record: &log::Record) {
                (self.0)(record)
            }
            fn flush(&self) {}
        }

        Self::from(Box::new(CallShim(func)) as Box<log::Log>)
    }
}

impl Default for Dispatch {
    /// Returns a logger configuration that does nothing with log records.
    ///
    /// Equivalent to [`Dispatch::new`].
    ///
    /// [`Dispatch::new`]: #method.new
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for Dispatch {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        struct LevelsDebug<'a>(&'a [(Cow<'static, str>, log::LevelFilter)]);
        impl<'a> fmt::Debug for LevelsDebug<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.debug_map()
                    .entries(self.0.iter().map(|t| (t.0.as_ref(), t.1)))
                    .finish()
            }
        }
        struct FiltersDebug<'a>(&'a [Box<Filter>]);
        impl<'a> fmt::Debug for FiltersDebug<'a> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.debug_list()
                    .entries(self.0.iter().map(|_| "<filter closure>"))
                    .finish()
            }
        }
        f.debug_struct("Dispatch")
            .field(
                "format",
                &self.format.as_ref().map(|_| "<formatter closure>"),
            )
            .field("children", &self.children)
            .field("default_level", &self.default_level)
            .field("levels", &LevelsDebug(&self.levels))
            .field("filters", &FiltersDebug(&self.filters))
            .finish()
    }
}

impl fmt::Debug for OutputInner {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            OutputInner::Stdout {
                ref stream,
                ref line_sep,
            } => f
                .debug_struct("Output::Stdout")
                .field("stream", stream)
                .field("line_sep", line_sep)
                .finish(),
            OutputInner::Stderr {
                ref stream,
                ref line_sep,
            } => f
                .debug_struct("Output::Stderr")
                .field("stream", stream)
                .field("line_sep", line_sep)
                .finish(),
            OutputInner::File {
                ref stream,
                ref line_sep,
            } => f
                .debug_struct("Output::File")
                .field("stream", stream)
                .field("line_sep", line_sep)
                .finish(),
            OutputInner::Writer { ref line_sep, .. } => f
                .debug_struct("Output::Writer")
                .field("stream", &"<unknown writer>")
                .field("line_sep", line_sep)
                .finish(),
            OutputInner::Sender {
                ref stream,
                ref line_sep,
            } => f
                .debug_struct("Output::Sender")
                .field("stream", stream)
                .field("line_sep", line_sep)
                .finish(),
            #[cfg(feature = "syslog-3")]
            OutputInner::Syslog3(_) => f
                .debug_tuple("Output::Syslog3")
                .field(&"<unprintable syslog::Logger>")
                .finish(),
            #[cfg(feature = "syslog-4")]
            OutputInner::Syslog4Rfc3164 { .. } => f
                .debug_tuple("Output::Syslog4Rfc3164")
                .field(&"<unprintable syslog::Logger>")
                .finish(),
            #[cfg(feature = "syslog-4")]
            OutputInner::Syslog4Rfc5424 { .. } => f
                .debug_tuple("Output::Syslog4Rfc5424")
                .field(&"<unprintable syslog::Logger>")
                .finish(),
            OutputInner::Dispatch(ref dispatch) => {
                f.debug_tuple("Output::Dispatch").field(dispatch).finish()
            }
            OutputInner::SharedDispatch(_) => f
                .debug_tuple("Output::SharedDispatch")
                .field(&"<built Dispatch logger>")
                .finish(),
            OutputInner::OtherBoxed { .. } => f
                .debug_tuple("Output::OtherBoxed")
                .field(&"<boxed logger>")
                .finish(),
            OutputInner::OtherStatic { .. } => f
                .debug_tuple("Output::OtherStatic")
                .field(&"<boxed logger>")
                .finish(),
            OutputInner::Panic => f.debug_tuple("Output::Panic").finish(),
        }
    }
}

impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}