Struct Logger

Source
pub struct Logger { /* private fields */ }

Implementations§

Source§

impl Logger

Source

pub fn set_format(&self, template: &str) -> &Self

Examples found in repository?
examples/custom_format.rs (line 21)
4fn main() {
5    // Try different built-in formats
6    logger().use_simple_format();
7    info!("Simple format");
8    warn!("Just symbol and message");
9
10    // Detailed format with timestamp
11    logger().use_detailed_format();
12    info!("Detailed format");
13    error!("With timestamp");
14
15    // Debug format with file location
16    logger().use_debug_format();
17    info!("Debug format");
18    warn!("With file location");
19
20    // Custom format
21    logger().set_format("{datetime} | {pid}:{thread_id} | {level} | {message}");
22    info!("Custom format");
23
24    // Format with context
25    let _ctx = logger().add_context("user", "admin");
26    logger().set_format("[{level}] {context}{message} ({file}:{line})");
27    info!("Message with context");
28
29    // Complex format showing all options
30    logger().set_format(concat!(
31        "Time: {time} | ",
32        "Date: {date} | ",
33        "Thread: {thread} | ",
34        "PID: {pid} | ",
35        "Level: {level} ({symbol}) | ",
36        "{context}",
37        "Message: {message}"
38    ));
39
40    thread::spawn(|| {
41        info!("Shows all available placeholders");
42    })
43    .join()
44    .unwrap();
45}
Source

pub fn use_simple_format(&self) -> &Self

Examples found in repository?
examples/custom_format.rs (line 6)
4fn main() {
5    // Try different built-in formats
6    logger().use_simple_format();
7    info!("Simple format");
8    warn!("Just symbol and message");
9
10    // Detailed format with timestamp
11    logger().use_detailed_format();
12    info!("Detailed format");
13    error!("With timestamp");
14
15    // Debug format with file location
16    logger().use_debug_format();
17    info!("Debug format");
18    warn!("With file location");
19
20    // Custom format
21    logger().set_format("{datetime} | {pid}:{thread_id} | {level} | {message}");
22    info!("Custom format");
23
24    // Format with context
25    let _ctx = logger().add_context("user", "admin");
26    logger().set_format("[{level}] {context}{message} ({file}:{line})");
27    info!("Message with context");
28
29    // Complex format showing all options
30    logger().set_format(concat!(
31        "Time: {time} | ",
32        "Date: {date} | ",
33        "Thread: {thread} | ",
34        "PID: {pid} | ",
35        "Level: {level} ({symbol}) | ",
36        "{context}",
37        "Message: {message}"
38    ));
39
40    thread::spawn(|| {
41        info!("Shows all available placeholders");
42    })
43    .join()
44    .unwrap();
45}
Source

pub fn use_detailed_format(&self) -> &Self

Examples found in repository?
examples/custom_format.rs (line 11)
4fn main() {
5    // Try different built-in formats
6    logger().use_simple_format();
7    info!("Simple format");
8    warn!("Just symbol and message");
9
10    // Detailed format with timestamp
11    logger().use_detailed_format();
12    info!("Detailed format");
13    error!("With timestamp");
14
15    // Debug format with file location
16    logger().use_debug_format();
17    info!("Debug format");
18    warn!("With file location");
19
20    // Custom format
21    logger().set_format("{datetime} | {pid}:{thread_id} | {level} | {message}");
22    info!("Custom format");
23
24    // Format with context
25    let _ctx = logger().add_context("user", "admin");
26    logger().set_format("[{level}] {context}{message} ({file}:{line})");
27    info!("Message with context");
28
29    // Complex format showing all options
30    logger().set_format(concat!(
31        "Time: {time} | ",
32        "Date: {date} | ",
33        "Thread: {thread} | ",
34        "PID: {pid} | ",
35        "Level: {level} ({symbol}) | ",
36        "{context}",
37        "Message: {message}"
38    ));
39
40    thread::spawn(|| {
41        info!("Shows all available placeholders");
42    })
43    .join()
44    .unwrap();
45}
Source

pub fn use_debug_format(&self) -> &Self

Examples found in repository?
examples/custom_format.rs (line 16)
4fn main() {
5    // Try different built-in formats
6    logger().use_simple_format();
7    info!("Simple format");
8    warn!("Just symbol and message");
9
10    // Detailed format with timestamp
11    logger().use_detailed_format();
12    info!("Detailed format");
13    error!("With timestamp");
14
15    // Debug format with file location
16    logger().use_debug_format();
17    info!("Debug format");
18    warn!("With file location");
19
20    // Custom format
21    logger().set_format("{datetime} | {pid}:{thread_id} | {level} | {message}");
22    info!("Custom format");
23
24    // Format with context
25    let _ctx = logger().add_context("user", "admin");
26    logger().set_format("[{level}] {context}{message} ({file}:{line})");
27    info!("Message with context");
28
29    // Complex format showing all options
30    logger().set_format(concat!(
31        "Time: {time} | ",
32        "Date: {date} | ",
33        "Thread: {thread} | ",
34        "PID: {pid} | ",
35        "Level: {level} ({symbol}) | ",
36        "{context}",
37        "Message: {message}"
38    ));
39
40    thread::spawn(|| {
41        info!("Shows all available placeholders");
42    })
43    .join()
44    .unwrap();
45}
Source

pub fn verbose(&self, enabled: bool) -> &Self

Examples found in repository?
examples/threads.rs (line 14)
12fn main() {
13    // Enable verbose mode globally
14    logger().verbose(true);
15
16    info!("This is an info message from main on the main thread");
17
18    thread::spawn(|| {
19        debug!("This is a debug message from another thread");
20    })
21    .join()
22    .unwrap();
23
24    function_log();
25
26    thread::spawn(|| {
27        function_thread_log();
28    })
29    .join()
30    .unwrap();
31}
More examples
Hide additional examples
examples/verbose.rs (line 5)
3fn main() {
4    // Enable verbose mode globally
5    logger().verbose(true);
6
7    info!("This is an info message");
8    let a = 1337;
9    info!("This is an info message with a variable: {}", a);
10    log!(
11        LogLevel::INFO,
12        "This is an info message with different syntactic sugar {}",
13        a
14    );
15    debug!("This is a debug message");
16    warn!("This is a warning message");
17    error!("This is an error message");
18    success!("This is a success message");
19    failure!("This is a failure message");
20}
examples/thread_safety.rs (line 7)
5fn main() {
6    // Enable verbose mode to see thread information
7    logger().verbose(true);
8
9    // Spawn multiple threads that log simultaneously
10    let mut handles = vec![];
11
12    for i in 0..3 {
13        let handle = thread::spawn(move || {
14            let _ctx = logger().add_context("thread_id", i.to_string());
15
16            for j in 0..3 {
17                info!("Message {} from thread {}", j, i);
18                thread::sleep(Duration::from_millis(100));
19            }
20        });
21
22        handles.push(handle);
23    }
24
25    // Wait for all threads to finish
26    for handle in handles {
27        handle.join().unwrap();
28    }
29}
Source

pub fn min_level(&self, level: LogLevel) -> &Self

Examples found in repository?
examples/filtering.rs (line 5)
3fn main() {
4    // Set minimum log level to WARN - this will hide DEBUG and INFO messages
5    logger().min_level(LogLevel::WARN);
6
7    debug!("This debug message won't show");
8    info!("This info message won't show");
9    warn!("This warning will show!");
10    error!("This error will show!");
11
12    // Change minimum level back to DEBUG to show everything
13    logger().min_level(LogLevel::DEBUG);
14
15    debug!("Now this debug message shows");
16    info!("And this info message too");
17}
Source

pub fn set_writer(&self, writer: Box<dyn Write + Send>) -> Result<()>

Examples found in repository?
examples/output_redirection.rs (line 10)
4fn main() -> std::io::Result<()> {
5    // First log to stdout
6    info!("This goes to terminal");
7
8    // Redirect to a file
9    let log_file = File::create("test.log")?;
10    logger().set_writer(Box::new(log_file))?;
11
12    info!("This goes to test.log");
13    warn!("This warning also goes to test.log");
14
15    Ok(())
16}
Source

pub fn add_context<K, V>(&self, key: K, value: V) -> ContextGuard
where K: Into<String>, V: Into<String>,

Examples found in repository?
examples/context.rs (line 5)
3fn scan_ports(host: &str) {
4    // Add context that will be included in all logs in this scope
5    let _host_ctx = logger().add_context("host", host);
6
7    info!("Starting port scan");
8
9    // Add another context
10    let _scan_ctx = logger().add_context("scan_type", "TCP");
11    warn!("Found open port 80"); // Will include both host and scan_type
12
13    // scan_ctx is dropped here, removing "scan_type" from context
14}
15
16fn main() {
17    let _req_id = logger().add_context("request_id", "12345");
18
19    info!("Starting application"); // Includes request_id
20
21    scan_ports("example.com"); // Includes request_id and temporarily host
22
23    info!("Finished!"); // Only includes request_id again
24}
More examples
Hide additional examples
examples/thread_safety.rs (line 14)
5fn main() {
6    // Enable verbose mode to see thread information
7    logger().verbose(true);
8
9    // Spawn multiple threads that log simultaneously
10    let mut handles = vec![];
11
12    for i in 0..3 {
13        let handle = thread::spawn(move || {
14            let _ctx = logger().add_context("thread_id", i.to_string());
15
16            for j in 0..3 {
17                info!("Message {} from thread {}", j, i);
18                thread::sleep(Duration::from_millis(100));
19            }
20        });
21
22        handles.push(handle);
23    }
24
25    // Wait for all threads to finish
26    for handle in handles {
27        handle.join().unwrap();
28    }
29}
examples/custom_format.rs (line 25)
4fn main() {
5    // Try different built-in formats
6    logger().use_simple_format();
7    info!("Simple format");
8    warn!("Just symbol and message");
9
10    // Detailed format with timestamp
11    logger().use_detailed_format();
12    info!("Detailed format");
13    error!("With timestamp");
14
15    // Debug format with file location
16    logger().use_debug_format();
17    info!("Debug format");
18    warn!("With file location");
19
20    // Custom format
21    logger().set_format("{datetime} | {pid}:{thread_id} | {level} | {message}");
22    info!("Custom format");
23
24    // Format with context
25    let _ctx = logger().add_context("user", "admin");
26    logger().set_format("[{level}] {context}{message} ({file}:{line})");
27    info!("Message with context");
28
29    // Complex format showing all options
30    logger().set_format(concat!(
31        "Time: {time} | ",
32        "Date: {date} | ",
33        "Thread: {thread} | ",
34        "PID: {pid} | ",
35        "Level: {level} ({symbol}) | ",
36        "{context}",
37        "Message: {message}"
38    ));
39
40    thread::spawn(|| {
41        info!("Shows all available placeholders");
42    })
43    .join()
44    .unwrap();
45}
Source

pub fn should_log(&self, level: LogLevel) -> bool

Source

pub fn write_log( &self, level: LogLevel, message: &str, file: &str, line: u32, ) -> Result<()>

Trait Implementations§

Source§

impl Default for Logger

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !Freeze for Logger

§

impl RefUnwindSafe for Logger

§

impl Send for Logger

§

impl Sync for Logger

§

impl Unpin for Logger

§

impl UnwindSafe for Logger

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.