Files
addr2line
adler
aho_corasick
ansi_term
arraydeque
as_slice
atty
backtrace
base64
bincode_core
bitflags
byteorder
bytes
capnp
capnp_futures
capnp_rpc
cfg_if
chrono
clap
ctrlc
derivative
dlib
downcast_rs
enumflags2
enumflags2_derive
evdev_rs
evdev_sys
failure
failure_derive
flexi_logger
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
generic_array
getrandom
gimli
glob
hash32
heapless
hid_io_core
hid_io_protocol
hidapi
install_service
lazy_static
libc
libloading
libudev_sys
log
memchr
memmap
miniz_oxide
mio
nanoid
nix
num_cpus
num_enum
num_enum_derive
num_integer
num_traits
object
once_cell
open
pem
pin_project_lite
pin_utils
ppv_lite86
proc_macro2
proc_macro_hack
proc_macro_nested
quote
rand
rand_chacha
rand_core
rcgen
regex
regex_syntax
remove_dir_all
ring
rustc_demangle
rustls
scoped_tls
sct
serde
serde_derive
slab
smallvec
spin
stable_deref_trait
strsim
syn
synstructure
sys_info
tempfile
textwrap
thiserror
thiserror_impl
time
tokio
future
io
loom
macros
net
park
runtime
stream
sync
task
time
util
tokio_macros
tokio_rustls
tokio_util
typenum
udev
uhid_virt
uhidrs_sys
unicode_width
unicode_xid
untrusted
vec_map
wayland_client
wayland_commons
wayland_sys
webpki
which
x11
xcb
xkbcommon
yansi
yasna
zwp_virtual_keyboard
  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
use crate::log_specification::LogSpecification;
use crate::primary_writer::PrimaryWriter;
use crate::writers::LogWriter;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

/// Allows reconfiguring the logger programmatically.
///
/// # Example
///
/// Obtain the `LoggerHandle` (using `.start()`):
/// ```rust
/// # use flexi_logger::{Logger, LogSpecBuilder};
/// let mut logger = Logger::with_str("info")
///     // ... your logger configuration goes here, as usual
///     .start()
///     .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e));
///
/// // ...
/// ```
///
/// You can permanently exchange the log specification programmatically, anywhere in your code:
///
/// ```rust
/// # use flexi_logger::{Logger, LogSpecBuilder};
/// # let mut logger = Logger::with_str("info")
/// #     .start()
/// #     .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e));
/// // ...
/// logger.parse_new_spec("warn");
/// // ...
/// ```
///
/// However, when debugging, you often want to modify the log spec only temporarily, for  
/// one or few method calls only; this is easier done with the following method, because
/// it allows switching back to the previous spec:
///
/// ```rust
/// # use flexi_logger::{Logger, LogSpecBuilder};
/// #    let mut logger = Logger::with_str("info")
/// #        .start()
/// #        .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e));
/// logger.parse_and_push_temp_spec("trace");
/// // ...
/// // critical calls
/// // ...
///
/// logger.pop_temp_spec();
/// // Continue with the log spec you had before.
/// // ...
/// ```
#[derive(Clone)]
pub struct LoggerHandle {
    spec: Arc<RwLock<LogSpecification>>,
    spec_stack: Vec<LogSpecification>,
    primary_writer: Arc<PrimaryWriter>,
    other_writers: Arc<HashMap<String, Box<dyn LogWriter>>>,
}
impl LoggerHandle {
    pub(crate) fn new(
        spec: Arc<RwLock<LogSpecification>>,
        primary_writer: Arc<PrimaryWriter>,
        other_writers: Arc<HashMap<String, Box<dyn LogWriter>>>,
    ) -> Self {
        Self {
            spec,
            spec_stack: Vec::default(),
            primary_writer,
            other_writers,
        }
    }

    #[cfg(feature = "specfile_without_notification")]
    pub(crate) fn current_spec(&self) -> Arc<RwLock<LogSpecification>> {
        Arc::clone(&self.spec)
    }

    //
    pub(crate) fn reconfigure(&self, mut max_level: log::LevelFilter) {
        for w in self.other_writers.as_ref().values() {
            max_level = std::cmp::max(max_level, w.max_log_level());
        }
        log::set_max_level(max_level);
    }

    /// Replaces the active `LogSpecification`.
    pub fn set_new_spec(&mut self, new_spec: LogSpecification) {
        let max_level = new_spec.max_level();
        self.spec.write().unwrap(/* catch and expose error? */).update_from(new_spec);
        self.reconfigure(max_level);
    }

    /// Tries to replace the active `LogSpecification` with the result from parsing the given String.
    pub fn parse_new_spec(&mut self, spec: &str) {
        self.set_new_spec(LogSpecification::parse(spec).unwrap_or_else(|e| {
            eprintln!(
                "[flexi_logger] LoggerHandle::parse_new_spec(): failed with {}",
                e
            );
            LogSpecification::off()
        }))
    }

    /// Replaces the active `LogSpecification` and pushes the previous one to a Stack.
    pub fn push_temp_spec(&mut self, new_spec: LogSpecification) {
        self.spec_stack
            .push(self.spec.read().unwrap(/* catch and expose error? */).clone());
        self.set_new_spec(new_spec);
    }

    /// Tries to replace the active `LogSpecification` with the result from parsing the given String
    ///  and pushes the previous one to a Stack.
    pub fn parse_and_push_temp_spec(&mut self, new_spec: &str) {
        self.spec_stack
            .push(self.spec.read().unwrap(/* catch and expose error? */).clone());
        self.set_new_spec(LogSpecification::parse(new_spec).unwrap_or_else(|e| {
            eprintln!(
                "[flexi_logger] LoggerHandle::parse_new_spec(): failed with {}, \
                 falling back to empty log spec",
                e
            );
            LogSpecification::off()
        }));
    }

    /// Reverts to the previous `LogSpecification`, if any.
    pub fn pop_temp_spec(&mut self) {
        if let Some(previous_spec) = self.spec_stack.pop() {
            self.set_new_spec(previous_spec);
        }
    }

    /// Flush all writers.
    pub fn flush(&self) {
        self.primary_writer.flush().ok();
        for writer in self.other_writers.values() {
            writer.flush().ok();
        }
    }

    /// Shutdown all participating writers.
    ///
    /// This method is supposed to be called at the very end of your program, if
    ///
    /// - you use buffering
    ///   (to ensure that all buffered log lines are flushed before the program terminates)
    /// - you use your own writer(s) (in case they need to cleanup resources)
    /// - or if you want to securely shutdown the cleanup-thread of the `FileLogWriter`
    ///   (if you use a [`Cleanup`](crate::Cleanup) strategy with compressing,
    ///   and your process terminates
    ///   without correctly shutting down the cleanup-thread, then you might stop the cleanup-thread
    ///   while it is compressing a log file, which can leave unexpected files in the filesystem)
    ///
    /// See also [`LogWriter::shutdown`](crate::writers::LogWriter::shutdown).
    pub fn shutdown(&self) {
        self.primary_writer.flush().ok();
        if let PrimaryWriter::Multi(writer) = &*self.primary_writer {
            writer.shutdown();
        }
        for writer in self.other_writers.values() {
            writer.shutdown();
        }
    }

    // Allows checking the logs written so far to the writer
    #[doc(hidden)]
    pub fn validate_logs(&self, expected: &[(&'static str, &'static str, &'static str)]) {
        self.primary_writer.validate_logs(expected)
    }
}