#slog #macros

slog-try

Convenience macros for logging with an optional slog Logger

5 releases (2 stable)

1.0.1 Mar 13, 2021
1.0.0 Mar 9, 2021
0.2.0 Jul 2, 2018
0.1.1 Mar 25, 2018
0.1.0 Sep 1, 2017

#202 in Debugging

Download history 2725/week @ 2022-06-09 2652/week @ 2022-06-16 2176/week @ 2022-06-23 2611/week @ 2022-06-30 3565/week @ 2022-07-07 4247/week @ 2022-07-14 2699/week @ 2022-07-21 2016/week @ 2022-07-28 2919/week @ 2022-08-04 1159/week @ 2022-08-11 2425/week @ 2022-08-18 3013/week @ 2022-08-25 5034/week @ 2022-09-01 3136/week @ 2022-09-08 1318/week @ 2022-09-15 1584/week @ 2022-09-22

11,383 downloads per month
Used in fewer than 6 crates

MIT/Apache

18KB
384 lines

slog-try

Convenience macros for logging with an optional slog Logger.

NOTE - See the bottom of this README for another method of using a Logger that doesn't require Option<Logger>

Current Release

docs.rs Crates.io Crates.io Crates.io codecov CI

Required dependencies

Add slog-try as a dependency in your Cargo.toml file.

[dependencies]
slog-try = "1"

Project setup

Add use statements for the macros you wish to use:

use slog_try::try_info;

Usage example

Consider HasOptLogger, a data strcuture with an optionally attachable logger:

#[derive(Default)]
struct HasOptLogger {
    logger: Option<Logger>,
}

The macros contained in slog-try encapsulate the required boilerplate to use this logger without verifying whether the optional field actually contains a logger or not:

let mut opt_logger = HasOptLogger { logger: None };

// Try to log even if no logger exist
try_info!(opt_logger.logger, "You won't see me output.  The logger is None."; "opt" => "None");
try_info!(opt_logger.logger, #"imatag", "You won't see me output.  The logger is None."; "opt" => "None");

// Setup a `Logger`
let plain = slog_term::PlainSyncDecorator::new(::std::io::stdout());
let logger = Logger::root(slog_term::FullFormat::new(plain)
    .build()
    .fuse(), o!("surname" => "Lava"));

opt_logger.logger = Some(logger);

// Call again with the new attached logger
try_info!(opt_logger.logger, "You will see me output!"; "opt" => "Some");
try_info!(opt_logger.logger, #"imatag", "You will see me output!"; "opt" => "Some");

Using a Discard Logger

You can use slogs Discard drain in lieu of the Option wrapped logger. Like the try_* macros, in case of a none present logger, the discarding logger is going to drop all incoming messages.

How to initialize a discarding logger

use slog::{Logger, Discard, o};

fn main() {
    let logger = Logger::root(Discard, o!());
    info!(logger, "nothing happens");
}

Dependencies

~140KB